简体   繁体   English

如何最好地在 Angular2 中使用 takeUntil 取消订阅 observable

[英]Hows best to unsubscribe from an observable using a takeUntil in Angular2

Hows best to unsubscribe from an observable using a takeUntil.如何最好地使用 takeUntil 取消订阅 observable。

From what I understand takeUntil automatically does the complete for you.据我所知,takeUntil 会自动为您完成。

Below is how I normally do a unsubscribe from an observable.以下是我通常如何取消订阅 observable。 But not sure if done correctly.但不确定是否正确完成。 Do I really need the "this.destroyed$.complete();"我真的需要“this.destroyed$.complete();”吗? if takeUntil does the complete for me?如果 takeUntil 对我来说完成了吗?

This is my current attempt that works but unsure if best method:这是我目前的尝试,但不确定是否是最佳方法:

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

 ngOnIt(): void {
    this.serviceA.getData
      .takeUntil(this.$destroyed)
      .subscribe(val => {
        console.log('Current value:', val);
      });
  };

  ngOnDestroy(): void {
    this.destroyed$.next();
    this.destroyed$.complete();
  };

I was thinking of removing the .complete in the ngOnDestory but not sure if that would cause memory leaks?我正在考虑删除 ngOnDestory 中的 .complete 但不确定这是否会导致内存泄漏?

Personally I prefer this solution, have another subject just to handle unsubscribe and mix up with takeUntil probably make things too complex我个人更喜欢这个解决方案,有另一个主题只是为了处理取消订阅并与 takeUntil 混淆可能会使事情变得太复杂

 private _subscriptions:Subscription[];

 ngOnIt(): void {
  this._subscriptions.push(this.serviceA.getData
  .subscribe(val => {
    console.log('Current value:', val);
  })
   )
};

ngOnDestroy(): void {
this._subscriptions.foreach(subs=>{ subs.unsubscribe()})
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular2:取消订阅服务中的 http observable - Angular2: Unsubscribe from http observable in Service Angular取消订阅BehaviorSubject为Observable - Angular unsubscribe from BehaviorSubject as Observable 在 rxjs 中,如何使用 takeUntil 或 takeWhile 取消订阅“内部”“间隔”可观察量 - In rxjs, how to unsubscribe from "inner" "interval" observables using takeUntil or takeWhile 在使用takeUntil模式取消订阅Observable时,是否需要完成主题? - Is completing the Subject necessary when using the takeUntil pattern to unsubscribe from Observables? Angular + RxJS:使用takeUntil vs简单取消订阅? - Angular + RxJS: use of takeUntil vs simple unsubscribe? Angular 6使用takeUntil防止组件中的多个Observable内存泄漏 - Angular 6 Prevent memory leaks multiple Observable in a component using takeUntil 如何取消订阅或处理Angular2或RxJS中可观察到的间隔? - How to unsubscribe or dispose an interval observable on condition in Angular2 or RxJS? 在永远不会销毁的组件中,Angular2 / 4不可订阅 - Angular2/4 unsubscribe observable in a component which never be destroyed 使用takeUntil break单元测试取消订阅Angular Observable - Unsubscribing Angular Observable using takeUntil break unit test 我是否需要取消订阅 Angular Observable? - Do I need to unsubscribe from an Angular Observable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM