pratik jaiswal
pratik jaiswal

Reputation: 2065

angular rxjs subscribe to second observable onlly if first observable is null

I have two methods that return observables. If first returns some data then no need to call the second method. But if the first method returns null then only call the second method.

getdefaultAddress(id) : Observable<Address[]> { 
    return this.http.get<Address[]>(this.url + 'users/' + id + '/addresses' + '?filter[where][default]=true')
  }

getFirstAddress(id): Observable<any>{
    return this.http.get<any>(this.url + 'users/' + id +'/addresses?filter[limit]=1'  )
  }

I can easily do this after subscribing to the first observable using if-else. Like

this.getdefaultAddress(id).subscibe(data =>{
    if(data) {
      // do something
    }

    else {
      this.getFirstAddress(id).subscibe(data =>{
        // do something
      })
    }
  })

Now how can I check this without really subscribing to first observable? Any rxjs operator?

Thank you in advance

Upvotes: 5

Views: 6245

Answers (4)

Eugene P.
Eugene P.

Reputation: 1814

If you mean you want to get data from some store, and, if it is not there, get it from an API, here is what you should do:

import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

this.getDataFromStorage().pipe(
  switchMap(data => data && data.length ? of(data) : this.requestDataFromAPI())
);

Upvotes: 1

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

const source1$: Observable<T| null>;
const source2$: Observable<T>;

const finalSource$ = source1$.pipe(
  switchMap(value => value ? of(value) : source2$) 
)

You return the outer source as long as it has an value. The moment/event it gets undefined/null you switch to the source2$.

Upvotes: 7

Malcor
Malcor

Reputation: 2721

I belive you can use a switchMap operator, I cant test at the moment.

You're basically switching to a new inner observable when the source emits.

this.getdefaultAddress(id).pipe(
  switchMap(data => {
    if (!data) {
      return this.getFirstAddress(id);
    }
  })
);

Upvotes: 1

martin
martin

Reputation: 96891

It's better to use for example concatMap:

import { EMPTY } from 'rxjs';
import { concatMap } from 'rxjs/operators';

this.getdefaultAddress(id)
  .pipe(
    concatMap(data => data === null ? EMPTY : this.getFirstAddress(id)),
  )
  .subscribe();

Upvotes: 3

Related Questions