使用 SubSink 而不是 Subscriptions 数组有什么意义

What is the point of using SubSink instead of a Subscriptions array

我刚刚观看了 John Papa 的 ngConf 视频,他谈到 SubSink 作为取消订阅 obversables 的最佳实践。

我实际上是在使用 Subscriptions[],然后将订阅推送到其中,然后在 cmp destroy 处取消订阅。

它们是我错过的东西还是使用 SubSink 只是提高了可读性?

采用这种方式至少有一个好处 - 您可以将此代码移出应用程序逻辑。因为退订只是清理(必须)。它与您在应用程序中创建的逻辑无关。

更进一步,您可以从组件中省略 ngOnDestroy,并创建一个实现了 NgOnDestroy 的适配器,并将所有逻辑放在那里。

import { OnDestroy } from '@angular/core';
import { SubSink } from './sub-sink';

/**
* A class that automatically unsubscribes all observables when 
* the object gets destroyed
*/
export class UnsubscribeOnDestroyAdapter implements OnDestroy {

/**The subscription sink object that stores all subscriptions */
subs = new SubSink();

/**
* The lifecycle hook that unsubscribes all subscriptions 
* when the component / object gets destroyed
*/
ngOnDestroy(): void {
   this.subs.unsubscribe();
}

How to automatically unsubscribe your RxJs observables

除此之外,它是一个非常小的包,只有几行代码。感谢分享:)

不安装第三方库的另一种方法是使用 .add() 方法对订阅进行分组

export class CustomerComponent implements OnInit, OnDestroy {
  constructor(
    private dataService: DataService
  ){}

  private subs = new Subscription();

  ngOnInit() {
    this.subs.add(this.dataService.getCustomer().subscribe());
    this.subs.add(this.dataService.getProducts().subscribe());
  }

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