0

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.

David
  • 3
  • 1
  • 1
    as a rule of thumb you should never subscribe inside another subscribe. do you need the result of getA() if A is true? or do you need only the result of getB ? – Zerotwelve Mar 17 '23 at 08:43

1 Answers1

0

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

wlf
  • 3,086
  • 1
  • 19
  • 29