Rxjs conditional switchMap based on a condition

user2010955 picture user2010955 · May 21, 2018 · Viewed 18.1k times · Source

I have a situation like the following:

myObservable1.pipe(
  switchMap((result1: MyObservable1) => {
    if (condition) {
      return myObservable2;
    } else {
      return of(null);
    }
  })
).subscribe(myObservable1 | myObservable2) => {

So if condition is false I only have to perform one request, if the condition is true, I have to chain the first request to the following one, they are essentially two requests to the server api.

Is there a better solution without returning that null?
Is there any conditional operator in RxJs?

Thanks!

Answer

Koraxos picture Koraxos · Nov 11, 2019

Another possibility is to use the operator iif in a SwitchMap.

https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif

https://rxjs-dev.firebaseapp.com/api/index/function/iif

but it can restrain the possibility to control specfic conditions on your Observable :

myObservable1
.pipe( 
      switchMap(result1 =>
               iif(() => condition
               , myObservable2
               , myObservable1
            )
      )
.subscribe(result => console.log(result)); 

Where you can replace 'condition' by a function returning a boolean. With a function :

myObservable1
    .pipe( 
          switchMap(result1 =>
                   iif(() => test(result1)
                   , myObservable2
                   , myObservable1
                )
          )
    .subscribe(result => console.log(result)); 

test(result1) : boolean {
     if(result1){
       // the iif() will return myObservable2
       return true;
     }else{
       /: the iif() will return myObservable1
       return false ;
     }
}

Like @amjuhire said , you can write with a filter and a switchMap :

myObservable1.pipe(
  filter((result1) => condition)
  switchMap((result1: MyObservable1) => {
    return myObservable2;
  })
).subscribe(result2 => { ... })

Another possibility given your example :

myObservable1.pipe(
  switchMap((result1: MyObservable1) => {
    if (condition) {
      return myObservable2;
    } else {
      return of(result1);
    }
  })
subscribe(result => console.log(result));

Or using EMPTY in the switchMap :

 myObservable1.pipe(
      switchMap((result1: MyObservable1) => {
        if (condition) {
          return myObservable2;
        } else {
          // Observable that immediately completes
          return EMPTY;
        }
      })
    subscribe(result2 => console.log(result2));

The problem here is that we don't know the type in your observable.

So i can't judge wich way is the better.

It also depends on how you want to handle the success/error between the different calls of your observable.