有什么时候我不需要在组件中处理取消订阅的例子吗?

Is there an example of when I don't need to handle unsubscribing in the component?

我已经习惯取消订阅我在我的组件中初始化的订阅。推荐的方法是像这样使用 takeUntil 运算符:

killSubscriptions: new Subject<any> = new Subject();

ngOnInit(){
   observableThing().pipe(takeUntil(this.killSubscriptions)).subscribe()
}

ngOnDestroy(){
  this.killSubscriptions.next();
  this.killSubscriptions.complete();
}

但前几天我在使用覆盖和门户服务实现自定义对话框时遇到了 this block of code in the middle of a method in the Angular Material Library

// When the dialog backdrop is clicked, we want to close it.
if (config.hasBackdrop) {
  overlayRef.backdropClick().subscribe(() => {
    if (!dialogRef.disableClose) {
      dialogRef.close();
    }
  });
}

如何清理此订阅?我唯一的猜测是当 overlayRef 被处理时,订阅被清除。但是怎么办?

还有其他不需要退订的时候吗?

简答

因为当 OverlayRef 被认为进入处置状态时它们完成了观察者。

this._backdropClick.complete();

Angular Material CDK source code

希望这对您有所帮助!通读源代码并尝试理解它是一种很好且有趣的学习方式:)

编辑:如果你不确定你的观察者是否会完成,那么你需要确保你主动退订以避免内存泄漏。您的 takeUntil 模式是一种可行的方法。您甚至可以将主题的类型从 any 更改为 void