2

I have a nested subscription which I believe is not good practice, and even though it usually works for me, in one instance it might causing me a problem.

How could I rewrite the following so it is not nested subscription?

this.pagesService.postReorderPages(ids).subscribe(res => {
                    if (res === "ok") {
                        console.log(res);
                        this.pagesService.getPages().subscribe(pages => {
                            this.pagesService.pagesBS.next(pages);
                            console.log(pages);
                        });
                    }
                });
Vojislav Kovacevic
  • 1,385
  • 2
  • 17
  • 28
  • 5
    Possible duplicate of [RxJs Observables nested subscriptions?](https://stackoverflow.com/questions/42888604/rxjs-observables-nested-subscriptions) – Moema Oct 03 '17 at 14:54

1 Answers1

4

I always recommend that people do their best to keep logic in their stream, and effects inside subscriptions or .do() callbacks. So i think your instincts about avoiding nested subscriptions are on point.

this.pagesService.postReorderPages( ids )
    .filter( res => res === 'ok' ) // moved logic from your subscription to stream
    .mergeMap( () => this.pagesService.getPages() )
    .subscribe( pages => {
        this.pagesService.pagesBS( pages );
    });

If you find yourself trying to avoid a nested subscription, oftentimes you want to reach for one of the *Map operators.

In rxjs, there are four of these

  1. mergeMap
  2. concatMap
  3. switchMap
  4. exhaustMap

They all behave a little differently, so I can't guarantee that this will implement your feature perfectly. But they all have the same signature, and they exist to handle "messy" nested subscribes (also sometimes referred to as "higher-order" or "meta" streams, in some libraries).

xtianjohns
  • 706
  • 3
  • 12