How can avoid nested subscribes with rxjs?

Viewed 215

I have rxjs nested observables, which work fine.

this.service.save(body).subscribe(
   () => {
       this.dialog.confirmDialog({
           title: '',
           message: 'Save okay',
           caption: 'OK'
       })
       .subscribe((yes) => {
            this.service.getGoal().subscribe(
             result => {
                 this.loading(result);
                }
              );
          });
       }
     });

The code does three things. First save object, secondly popup a confirmation window. Last call service to refresh the page. I use nested subscribe here. I know it is not good in theory and I should replace them with rxjs some map function. But I just don't know how?

2 Answers

This should be roughly equivalent without nesting subscriptions:

this.service.save(body).pipe(
  mergeMap(_ => this.dialog.confirmDialog({
    title: '',
    message: 'Save okay',
    caption: 'OK'
  })),
  mergeMap(yes => this.service.getGoal())
).subscribe(result =>
  this.loading(result)
);

You should use RxJs operators to make your observable stream cleaner. Depending on your use case, some common operators include mergeMap, switchMap, map, e.t.c.

Nesting subscribes can cause problems such as memory leaks.

Related