Close subscription on condition with takeUntil()

感情迁移 提交于 2019-12-04 05:51:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!