Easiest way to unsubscribe subscriptions Angular

跟風遠走 提交于 2019-12-05 20:48:01
Günter Zöchbauer
subscriptions = Subscription[];

someMethod() {
  this.subscriptions.push(http.get(...).map(...).subscribe(...));
}

ngOnDestroy() {
  this.subscriptions.forEach(s => s.unsubscribe());
}

When an observable completes, unsubscribing is redundant. Unsubscribing is only necessary for observables that continueally emit events without completing.

If you only want to receive a single (or otherwise limited number of events) you can control when the observable you subscribed to completes by using an operator like take(x), then after x events the observable will complete.

There's also another interesting way to do that :

@Component({ ... })
export class SomeComponent implements OnInit, OnDestroy {
  private componentDestroyed$ = new Subject();

  ...

  ngOnInit() {
    this.yourObs1$.takeUntil(componentDestroyed$).subscribe(...);
    this.yourObs2$.takeUntil(componentDestroyed$).subscribe(...);
    this.yourObs3$.takeUntil(componentDestroyed$).subscribe(...);
    ...
    this.yourObsX$.takeUntil(componentDestroyed$).subscribe(...);
  }

  ngOnDestroy() {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }
}

Here, you don't even need to keep track of a subscription and the way you read is more dev friendly (I think).

Ben Lesh explained it on Medium and I like this way to unsubscribe !

export class BaseComponent implements OnDestroy {

  protected alive$:  Subject<void> = new Subject<void>();
  ngOnDestroy(): void {
    // console.log("unsubscribing base component");
    this.alive$.next();
    this.alive$.complete();
  }
}

export class EveryComponent extends BaseComponent {
  this.AllObs1$.takeUntil(this.alive$).subscribe(...);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!