Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

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

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$"> 

Upvotes: 17

Views: 63249

Answers (5)

fredfred
fredfred

Reputation: 341

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

Upvotes: 10

jics
jics

Reputation: 2215

Using the @Deitsch I just made one change to avoid typescript errors:

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

I added the sign: ? before lenght property

Upvotes: 4

Deitsch
Deitsch

Reputation: 2178

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>

Upvotes: 6

sbarlabanov
sbarlabanov

Reputation: 21

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

Upvotes: 2

OJ Kwon
OJ Kwon

Reputation: 4641

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.

Upvotes: 11

Related Questions