Search code examples
angularngrxrxjs6ngrx-store

Close subscription on condition with takeUntil()


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


Solution

  • 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;
            }
        });