Following use case: A user can join 0...* groups. Each group has an ID and contains 0...* posts.
I subscribe to an Observable (to get the groups of the user he joined) and this returns an array of strings (the group IDs).
const groupIds$ = of(['a', 'b', 'c']);
If I only had one I would now use switchMap
and return this new observable and subscribe to it to get the posts from the group.
But so I have an array and so this isn't working. Does anyone has an idea which RxJS operator(s) can achieve this to get the posts from all groups?
Or does no operator for such use case exist and I have to do it separately at subscribe?
You can use ideally forkJoin
if you know you'll have all source Observables as an array:
groupIds$.pipe(
concatMap(groups => {
const observables = groups.map(id => ...);
return forkJoin(...observables);
})
).subscribe(...);
forkJoin
will emit a single array with all the results in the same order as in groupIds$
.
Eventually if you don't care about the order and just want to get all the results in parallel you can use merge
instead of forkJoin
(I mean the "Observable creation method" called merge
imported directly from rxjs
. Not the merge
operator from 'rxjs/operators'
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With