codependent
codependent

Reputation: 24452

RxJs - How to implement parallel HTTP requests when you have a variable number of requests to make

I am developing a Node.js API with Express, using the node-rest-client module to make http requests.

One of the API endpoints to develop is /api/v1/users/:userId that returns the full information of a user, its user info plus the detailed information about the departments he belongs to.

To get the information there are this backend REST services:

/users/:userId - Returns a JSON object with the user info plus the list of department ids, e.g.:

{ "name" : "xxx",
  "departments" : [1, 5 ,6, 8]
}

/departments/:departmentId - JSON object with the department info

{ 
  "id" : x,
  "name" : "xxx"
}

An invocation to /api/v1/users/1would need to call

  1. GET /user/1 -> { "name" : "user1" , "departments" : [1, ,5 ,7 ,8]}
  2. Get the department ids and make n calls to /departments/deparmentId
  3. After all the calls, compose the full JSON response and return it.

I would like to paralellize the requests using RxJs, so I guess it would be enough with using Rx.Observable.zip().

The point is, if I have an array of Observables, whose size is not fixed, representing every HTTP request call, how can I invoke Observable.zip()?

If the number of elements in the array where fixed I woud do it like this:

var observables = [ obs1, obs2 ];

Rx.Observable.zip( observables[0], observable[1], function(...){...});

But I don't know how many observables there are, so how can I call zip()?

Upvotes: 3

Views: 1300

Answers (2)

taras-d
taras-d

Reputation: 1827

Another way is to use forkJoin that can receive observables as array

Rx.Observable.forkJoin([obs1, ..., obsN]).subscribe(...);

Upvotes: 0

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

You can use the ... operator from es6,

var observables = [obs1, obs2, obs3, ...,  obsx];
Rx.Observable.zip(...observables, function() {});

Upvotes: 3

Related Questions