Ramesh Kumar
Ramesh Kumar

Reputation: 1

merge multiple parallel api response rxjs

Assume User class has a following structure

class User {
  id!: number;
  name!: string;
  friends!: User[];
  latestComments!: string[]
}

I have an api which respond with list of users with only id and name filed.

getUsers(): Observable<User[]>;

To get other details like friends and latest comments, there are two separate apis.

getLatestComments(is: number): Observable<string[]>;

and

getFriends(id: number): Observable<User[]>;

Problem Statement:

For all users of getUsers we need to call getLatestComments and getFreinds apis in parallel and update the user object.

Upvotes: 0

Views: 372

Answers (1)

Perry45
Perry45

Reputation: 86

Just look here: https://rxjs.dev/operator-decision-tree

You could use concatMap on the outer Observable and then use forkJoin on the inner parallel Observables. ConcatMap can pass the User data to the inner two. ForkJoin waits until the inner finished and all 3 can be processed further.

See console of this minimal example: https://stackblitz.com/edit/typescript-casjbg?devToolsHeight=33&file=index.ts

EDIT: I just revisted my answer and the exmaple was not 100% correct, if you get a list of User at once you have either call getComments and getFriends in parallel but sequentiell for each of the received Users (like so https://stackblitz.com/edit/typescript-3grnds?devToolsHeight=33&file=index.ts) or if you really want to call all getComments and getFriends for all User in parallel you have to do something like this: https://stackblitz.com/edit/typescript-grjtb2?devToolsHeight=33&file=index.ts But be careful if you get 100 Users you do 200 calls in parallel!!

Theoretically you can also mix up these approaches and do it in batches, so call all comments and friends for every 10 Users in the array at once, what ever your App or Api can handle....

Upvotes: 1

Related Questions