'Angular RXJS, how do I get all data in subscribe after using multiple mergeMap calls (sequentially)?

I'd like to get all data similar to how 'forkJoin' does it after making multiple HTTP calls sequentially using MergeMap.

this.dataService.getData1().pipe(
      mergeMap(response1 => this.dataService.getData2()),
      mergeMap(response2 => this.dataService.getData3()),
      mergeMap(response3 => this.dataService.getData4()),
    ).subscribe(

    //How do I get response1, response2, response3 and response4 here?

 )


Solution 1:[1]

If no observable's parameter depend on the previous call

you can use concat, which will play the observables is a sequence, each time waiting on the previous to finish (unlike merge)

var arr = [
  this.dataService.getData1(),
  this.dataPublicationsService.getData2(),
  this.dataPublicationsService.getData3(),
  this.dataPublicationsService.getData4(),
];
concat(...arr).pipe(toArray()).subscribe((a) => console.log(a));

If each call depends on the previous one there is no "clean" way to do it, you have to pass the data youself.

One way to achieve this is use forkJoin and the spread operator

class Foo {
  dataService: { getData1: () => Observable<number> };
  dataPublicationsService: {
    getData2: () => Observable<string>;
    getData3: () => Observable<number>;
    getData4: () => Observable<object>;
  };

  bar() {
    this.dataService
      .getData1()
      .pipe(
        mergeMap((response1) =>
          forkJoin([of(response1), this.dataPublicationsService.getData2()])
        ),
        mergeMap((rest) => // rest is [number, string]
          forkJoin([of([...rest]), this.dataPublicationsService.getData3()])
        ),
        mergeMap((rest) => rest is [number, string, number]
          forkJoin([of(...rest), this.dataPublicationsService.getData4()])
        )
      )
      .subscribe((rest) => {
         // [number, string, number, object]
      });
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1