[Fixed] What is the correct way to use forkJoin with an array containing nested arrays?

Issue

Given the following array of objects, I need to collect a series of observables from calls to an endpoint

const data = [
    {
        body: [{ id: 1 }, { id: 2 }],
    },
    {
        body: [{ id: 3 }],
    },
];

const requests = data.map((entry) => entry.body.map((item) => this.someService.query(item.id).pipe(take(1))));

The result of this operation is similar to this

[ [ 1, 2 ], [ 3 ] ]

or

[[Observable, Observable], [Observable]]

In other cases I have passed to forkJoin flat arrays of observables and I get the results I require. But in this case with an array of nested arrays. What is the correct way to use forkJoin with an array containing nested arrays?

Solution

You may want to try something along these lines. See inline comments for details.

const data = [
  {
    body: [{ id: 1 }, { id: 2 }]
  },
  {
    body: [{ id: 3 }]
  }
];

forkJoin(
  // for each item of data create an Observable, which is the result of
  // executing the inner forkJoin
  data.map(entry =>
    // the inner forkJoin executes an array of Observables obtained by 
    // invoking someService.query on each item of the body
    forkJoin(entry.body.map(item => someService.query(item.id).pipe(take(1))))
  )
).subscribe(console.log);

Here a stackblitz to test it

Leave a Reply

(*) Required, Your email will not be published