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$">
The RxJS isEmpty() operator returns an observable with a Boolean value indicating whether the observable was empty or not. It returns an output as true if the source observable is empty; otherwise, false.
Observables are declarative —that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
A fundamental aspect of observables is that when they complete, any subscriptions are automatically unsubscribed. As such, if you know an observable will complete then you do not need to worry about cleaning up any subscriptions.
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>
You can use defaultIfEmpty
operator to define some default value in case if the source observable is empty.
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)
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With