1. 使用takeUntil取消订阅

  1. export class TestComponent {
  2. constructor(private store: Store) { }
  3. private componentDestroyed: Subject<never> = new Subject();
  4. ngOnInit() {
  5. this.store
  6. .pipe(
  7. takeUntil(this.componentDestroyed),
  8. select(selectSiteGroupListState),
  9. )
  10. .subscribe(siteGroupList => {
  11. this.siteGroupEntities = siteGroupList.entities;
  12. }
  13. ngOnDestroy() {
  14. this.componentDestroyed.next();
  15. this.componentDestroyed.unsubscribe();
  16. }
  17. }

takeUntil实现的效果是使得流进入complete状态,以达到unsubscribe状态;
另外讨论subscription的unsubscribe属性,是指observer不再订阅某个流Observable,与complete是不同的概念。以报纸订阅作为比喻:complete指报纸报社不再发行报纸,因此也无从订阅;而unsubscribe指用户不再订阅,对流(报社)本身没有任何影响。

2. subscription取消订阅

  1. var observable1 = Rx.Observable.interval(400);
  2. var observable2 = Rx.Observable.interval(300);
  3. var subscription = observable1.subscribe(x => console.log('first: ' + x));
  4. var childSubscription = observable2.subscribe(x => console.log('second: ' + x));
  5. subscription.add(childSubscription);
  6. setTimeout(() => {
  7. // Unsubscribes BOTH subscription and childSubscription
  8. subscription.unsubscribe();
  9. }, 1000)

这种方法本质上就是将所有订阅的subscription存入列表里然后统一取消订阅。Subscription也有一个名为
remove(otherSubscription)的方法,用来撤销已经添加到其中的其他Subscription。