Rxjs - check if Observable is empty, without subscribing to it

37,247

Solution 1

In short, no.

By default Observable is unicast behaves similar to function, so emits value to observer once it is actually subscribed. It is important it is similar to function, subscribing is actual attempt to start those observables. If you think of typical function returns a value (or not), you won't be able to know until function is actually executes and returns its results. Same applies for Observable as well you can't have source's values until you subscribe it.

Solution 2

You can try using defaultIfEmpty operator (see description). Supposed your advertsPerUser return a number you could do this:

this.adverts$ = this.advertService.advertsPerUser().map(count => count > 0).defaultIfEmpty(false);

in html:

<div *ngIf="adverts$ | async">

or with rxjs version 6:

this.adverts$ = this.advertService.advertsPerUser().pipe(
    map(count => count > 0),
    defaultIfEmpty(false)
);

Solution 3

I had a similar issue where i wanted to check if my response, which is an array of a custom type, was empty or not. Here is my solution

<div *ngIf="(response$ | async).length == 0">
    <p>no results</p>
</div>

Solution 4

You can use defaultIfEmpty operator to define some default value in case if the source observable is empty.

Share:
37,247
Julius Dzidzevičius
Author by

Julius Dzidzevičius

Updated on July 09, 2022

Comments

  • Julius Dzidzevičius
    Julius Dzidzevičius almost 2 years

    I wonder is it possible to check if observable received any value. And I want this without subscribing to it, because I am too lazy to overwrite my current code. Problem is that I create observable in parent component and then passing it to child components. And I need only one tiny thing from it, so subscribing just for that, seems unnecessary...

    parent-component:

    adverts$: Observable<advert[]>;
        
    ngOnInit() {
        this.adverts$ = this.advertService.advertsPerUser();
    

    service:

    advertsPerUser() {
        return this.advertsKeysPerUser()
            .map(adKeys => adKeys.map(adKey => this.afDb.object('adverts/' + adKey.$key )))
            .flatMap(val => Observable.combineLatest(val) );
    }
    

    So my goal is in parent-component.html do something like:

    <div *ngIf="adverts$">