2
votes

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

4

4 Answers

4
votes
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$.

3
votes

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();
1
votes

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);
    }
  })
);
0
votes

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