问题
I have a subscription to get providers from a NgRx reducer. I want to use takeUntil()
to automatically close the subscription when is finally returns an array that has content:
// Fetch providers
this.store.pipe(select(reducer.getProviders))
// .takeUntil(reducer.getProviders.length > 0)
.subscribe(providers => {
if (providers) {
this.providers = providers;
// takeUntil(/** something **/);
}
});
Can someone help me with this?
I can't figure out how to make use of takeUntil()
回答1:
takeUntil
accepts an Observable. (Source: docs). For your case, it would make more sense to use takeWhile
, this will emit values as long as a particular condition is satisfied (Source: docs). Set the optional inclusive
property to true so that it will also emit the first item that didn't pass the predicate.
this.store.pipe(select(reducer.getProviders))
.takeWhile(reducer => reducer.getProviders.length == 0, true)
.subscribe(providers => {
if (providers) {
this.providers = providers;
}
});
回答2:
You're looking for takeWhile()
.
takeUntil()
's parameter is an observable, and once that observable emits it will stop taking values.
takeWhile()
's parameter is a predicate which determines whether to take values.
See the documentation for takeWhile on learn-rxjs: https://www.learnrxjs.io/operators/filtering/takewhile.html
takeWhile(predicate: function(value, index): boolean, inclusive?: boolean): Observable
Emit values until provided expression is false.
来源:https://stackoverflow.com/questions/57705917/close-subscription-on-condition-with-takeuntil