StaticName
StaticName

Reputation: 295

RxJs: get array of observables

I have following pseudocode

zip(
        ...[1, 2, 3].map((id) =>
          this.http.function1(id).pipe(
            mergeMap((obj1) => this.http.function2(obj1.id)),
            mergeMap((obj2) => this.http.function3(obj2.id)),
          ),
        ),
      ).subscribe((result) => {
        console.log('This should be an array of all the results of the requests to this.http.function3');
      });

I want the result of all the request together. How can I do this?

Upvotes: 1

Views: 227

Answers (1)

Joshua McCarthy
Joshua McCarthy

Reputation: 1842

Rather than zip(), I would emit each value of the array using from(), then at the end of your pipe, you can apply toArray() to combine all emitted values to an array after all HTTP requests have completed.

from([1, 2, 3]).pipe(
  mergeMap(id =>
    this.http.function1(id).pipe(
      mergeMap(obj1 => this.http.function2(obj1.id)),
      mergeMap(obj2 => this.http.function3(obj2.id))
    )
  ),
  toArray()
).subscribe(result=>{
  console.log('Result should now be an array from function3', result);
});

Upvotes: 1

Related Questions