Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: SwitchMap for Array of Strings

Tags:

rxjs

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?

like image 683
Paul Avatar asked Dec 18 '22 20:12

Paul


1 Answers

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').

like image 72
martin Avatar answered Feb 18 '23 23:02

martin