【问题标题】:Easiest way to unsubscribe subscriptions Angular取消订阅Angular的最简单方法
【发布时间】:2017-03-08 06:48:30
【问题描述】:

您好,我对 Angular 很陌生。我有大约 4 个数据库查询,每个查询都是 Subscriptions(rxjs/Rx)。所以我知道我需要取消订阅我的每个订阅以节省内存泄漏。如何优化通话?我的意思是,我不想调用每个订阅并一一取消订阅。我想在一个电话中完成所有取消订阅。对不起,如果这是一个愚蠢的问题。有什么想法吗?提前致谢

【问题讨论】:

标签: angular rxjs


【解决方案1】:
subscriptions = Subscription[];

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

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

当一个 observable 完成时,取消订阅是多余的。取消订阅仅对持续发出事件但未完成的 observables 是必需的。

如果您只想接收单个(或其他有限数量的事件),您可以使用take(x) 之类的运算符来控制您订阅的 observable 何时完成,然后在x 事件之后 observable 将完成。

【讨论】:

  • 我正在写一篇关于退订冗余的评论,但你的编辑速度更快:)。一些很好的阅读:stackoverflow.com/a/41177163/7447071
  • 黄金链接(如来自 carcant 的链接)。
  • @Günter,我知道当一个流完成时,它会在拆解中取消订阅,在这种情况下,我们不需要手动取消订阅。但是,我不清楚何时发起 http 调用以及用户在调用返回之前导航离开视图,或者它是否永远不会返回。我听说如果发生这种情况就会造成泄漏,您能否确认或否认?
  • 我不认为这是个问题,但我需要看一个具体的代码示例。
【解决方案2】:
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(...);
}

【讨论】:

    【解决方案3】:

    还有另一种有趣的方法:

    @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();
      }
    }
    

    在这里,您甚至不需要跟踪订阅,而且您阅读的方式对开发人员更友好(我认为)。

    Ben Lesh 在Medium 上解释了它,我喜欢这种退订方式!

    【讨论】:

      猜你喜欢
      • 2018-04-19
      • 2014-06-30
      • 2023-03-24
      • 2013-05-05
      • 2023-01-04
      • 2021-06-14
      • 2021-11-18
      • 1970-01-01
      • 2020-04-07
      相关资源
      最近更新 更多