主要区别在于思维方式……以及样板文件。
Without takeUntil
,当您的文件大小和代码行数增加时,您可能会得到类似的结果:
private subscription1: Subscription;
private subscription2: Subscription;
private subscription3: Subscription;
private subscription4: Subscription;
private subscription5: Subscription;
private subscription6: Subscription;
ngOnInit() {
this.subscription1 = this.service.method().subscribe(...);
this.subscription2 = this.service.method().subscribe(...);
this.subscription3 = this.service.method().subscribe(...);
this.subscription4 = this.service.method().subscribe(...);
this.subscription5 = this.service.method().subscribe(...);
this.subscription6 = this.service.method().subscribe(...);
}
ngOnDestroy() {
this.subscription1.unsubscribe();
this.subscription2.unsubscribe();
this.subscription3.unsubscribe();
this.subscription4.unsubscribe();
this.subscription5.unsubscribe();
this.subscription6.unsubscribe();
}
或者,您可以声明一个订阅数组并推送到其中。
两者似乎都不是很方便,如果您最终使用了许多包含订阅的方法,那么如果您不滚动到ngOnDestroy
.
另一方面,使用Subject
更具可读性:
private onDestroy$ = new Subject<void>();
ngOnInit() {
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
this.service.method().takeUntil(this.onDestroy$).subscribe(...);
}
ngOnDestroy() {
this.onDestroy$.next();
this.onDestroy$.complete();
}
即使订阅被划分到整个文件中,您也可以检查是否takeUntil(this.onDestroy$)
存在或不存在。
它也更接近 Rxjs 和处理流的思想。
现在,为了确保取消订阅某些内容,您可以使用 subscribe 的第三个参数:
this.service.method().takeUntil(this.onDestroy$).subscribe(
onNext => ...,
onError => ...,
onComplete => console.log('stream has been completed')
);
如果您不喜欢在 subscribe 方法中添加任何内容,您可以这样做:
this.service.method().takeUntil(this.onDestroy$)
.do({
complete => console.log('stream has been completed')
})
.subscribe();
如果你想进一步深入这个主题,你应该阅读这篇优秀的文章Ben Lesh: https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87