1

Suppose, I call one service returning observable and if it doesn't throw any error then should call another service which also returns observable.

What I have done is that I have called both separately such as one after the other but when I debug the back end it is simultaneously jumping between the 2 called apis and behaves abnormally.

this.taskServices.addService().subscribe((s) => {
     if(s) {
       this.taskServices.clean().subscribe(s=> {
     console.write('done')
  });
     }
});

The code might not be correct syntax wise since I typed using a cell phone but gives the idea.

1 Answers1

0

As mentioned in the comment provide by @MikeOne, subscribing inside another subscribe is a bad practice, is call, callback hell; for that, you must use High RxJs order operators such as mergeMap, switchMap, concatMap and exhaustMap, so depending on what you need, you will need to use one of them.

For instance, you could use mergeMap like this:

this.taskServices
      .addService()
      .pipe(
        mergeMap((response) => {
          if (response)
            return this.taskServices
              .clean()
              .pipe(tap(() => console.log('Done cleaning')));

          return of('nothing happened');
        })
      )
      .subscribe();
Andres2142
  • 2,622
  • 2
  • 14
  • 19