1. 使用takeUntil取消订阅
export class TestComponent {constructor(private store: Store) { }private componentDestroyed: Subject<never> = new Subject();ngOnInit() {this.store.pipe(takeUntil(this.componentDestroyed),select(selectSiteGroupListState),).subscribe(siteGroupList => {this.siteGroupEntities = siteGroupList.entities;}ngOnDestroy() {this.componentDestroyed.next();this.componentDestroyed.unsubscribe();}}
takeUntil实现的效果是使得流进入complete状态,以达到unsubscribe状态;
另外讨论subscription的unsubscribe属性,是指observer不再订阅某个流Observable,与complete是不同的概念。以报纸订阅作为比喻:complete指报纸报社不再发行报纸,因此也无从订阅;而unsubscribe指用户不再订阅,对流(报社)本身没有任何影响。
2. subscription取消订阅
var observable1 = Rx.Observable.interval(400);var observable2 = Rx.Observable.interval(300);var subscription = observable1.subscribe(x => console.log('first: ' + x));var childSubscription = observable2.subscribe(x => console.log('second: ' + x));subscription.add(childSubscription);setTimeout(() => {// Unsubscribes BOTH subscription and childSubscriptionsubscription.unsubscribe();}, 1000)
这种方法本质上就是将所有订阅的subscription存入列表里然后统一取消订阅。Subscription也有一个名为remove(otherSubscription)的方法,用来撤销已经添加到其中的其他Subscription。
