Home > Net >  Is there another way of having an IF statement inside nested subscriptions using RxJS?
Is there another way of having an IF statement inside nested subscriptions using RxJS?

Time:07-05

I need to assess the result of the first observable to determine if the second one should be subscribed to. From reading other threads and the RxJS documentation I can see that nested subscriptions should be avoided where possible. Below is an example:

    obs1().subscribe(result=> {
      if (result.status === 'success') {
        obs2().subscribe(() => {
          executeMethod();
        });
      }
    });

Any help or resources are greatly appreciated.

CodePudding user response:

It could look like this:

obs1().pipe(
    filter(result => result.status === 'success'),
    switchMap(() =>  obs2()),
).subscribe( //...
  • Related