apirxjsswitchmapconcatmapmergemap

RxJS how to call multi API with conditional


My situation:

If A is true { Call API 1 If B is true { Call API 2 } else { If B is true { Call API 2 } }

My current solution

if (A) {
  this.aservice.getA().subscribe((resA) => {
     if (B) {
        this.bservice.getB().subscribe((resB) => {
           console.log(res);
        });
     }
  });
} else if (B) {
  this.bservice.getB().subscribe((resB) => {
     console.log(res);
  });
}

Have any better solution? Please advise, thanks.


Solution

  • Your code is not very rxjs like (no operators), you can do something like this (untested):

    const callBIfRequired$ = iif(() => B, this.bservice.getB());
    
    result$ = iif(() => A, 
      this.aservice.getA().pipe(mergeMap(() => callBIfRequired$)),
      callBIfRequired$
    );
    
    result$.subscribe(console.log);