Close subscription on condition with takeUntil()

2020-05-03 11:23发布

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()

2条回答
混吃等死
2楼-- · 2020-05-03 11:42

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;
        }
    });
查看更多
虎瘦雄心在
3楼-- · 2020-05-03 12:04

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.

查看更多
登录 后发表回答