问题
I have an observable array, purchases$. In my angular 2 component I'd like to calculate the length of the array. I worry that the observable is never complete and thus my subscriptions end up piling up. If I do the following will the subscription be complete?
this.purchases$.subscribe((val) => {
val.length > 0 ? this.purchaseType = 'initial' : this.purchaseType = 'additional'
})
Once I have an initial value I am happy to unsubscribe.
Can I simple add .unsubscribe() to the end?
回答1:
What you have in your subscriptions doesn't affect the source Observable so if you want to unsubscribe you need to use an operator that completes the chain or unsubscribe manually.
For example if you know how many items you want to accept you can use take(N) or if it depends on a certain condition you can use takeWhile(). Or you can collect items with scan() and combine it with takeWhile() for example.
You can also unsubscribe right in your subscribe call:
this.purchases$.subscribe(function(val) {
if (condition) {
this.unsubscribe();
}
});
Note that in this case you can't use arrow functions () => ... because RxJS binds this context to the current Subscription object. That's why you can call this.unsubscribe() and unsubscribe (this is not a hack, it's intended to be used this way).
回答2:
Rather than imperatively unsubscribing, i'd recommend you use the first operator to make an observable that automatically completes after the first result is emitted:
this.purchases$.pipe(first()).subscribe((val) => {
val.length > 0 ? this.purchaseType = 'initial' : this.purchaseType = 'additiona';
})
来源:https://stackoverflow.com/questions/52500728/rxjs-calculating-observable-array-length-in-component