Hello
Hello

Reputation: 816

How can avoid nested subscribes with rxjs?

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?

Upvotes: 1

Views: 1204

Answers (2)

laudebugs
laudebugs

Reputation: 176

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.

Upvotes: 0

Mrk Sef
Mrk Sef

Reputation: 8022

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

Upvotes: 3

Related Questions