Angular 4 – 取消订阅的最佳方式

前端之家收集整理的这篇文章主要介绍了Angular 4 – 取消订阅的最佳方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很好奇我如何取消订阅我的所有订阅.我知道takeWhile()和takeUntil().我觉得takeUntil()对我来说更有用.

as far as I understand,takeWhile() take effects after we get the data. then unsubscribe until the component is destroy.

什么是使用takeUntil()而不使用它的区别.只是.unsubscribe()?

不使用takeUntil()

ngOnInit() {
 this.subscriptions = this._membeRSService.getMembers().subscribe(data => 
 this.members = data)
}

ngOnDestroy() {
 this.subscriptions.unsubscribe();
}

使用takeUntil

private destroyed$: Subject<{}> = new Subject();

ngOnInit() {
 this._membeRSService.getMembers().takeUntil(this.destroyed$).subscribe(data 
 => this.members = data)
}

ngOnDestroy() {
  this.destroyed$.next();
}

also how can I determine If I unsubscribe successfully?

主要区别在于思维方式……以及样板.

如果没有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

猜你在找的Angularjs相关文章