Fire Async Request In Parallel But Get Result In Order Using Rxjs

- 1 answer

For example:

Get 5 pages in parrallel using jquery ajax. When page2 return, do nothing. When page1 return, do something with page1 and page2.

// assume there is some operator that can do this, 
// then it might look like this?
Rx.Observable.range(1, 5).
someOperator(function(page) {
  return Rx.Observable.defer( () => $.get(page) );
}).scan(function(preVal, curItem) {
  return preVal;
}, []);


There exists the forkJoin operator which will run all observable sequences in parallel and collect their last elements. (quoted from the documentation). But if you use that one, you will have to wait for all 5 promises to resolve, or one of the 5 to be in error. It is the close equivalent to RSVP.all or jQuery.when. So that would not allow you to do something once you have the second. I mention it anyways in case it might be useful to you in another case.

Another possibility is to use concatMap which will allow you to receive the resolved promises in order. However, I don't have it clear that they will be launched in parallel, the second promise should start only when the first one has resolved.

Last option I can think about is to use merge(2), that should run two promises in parallel, and at anytime they will only be two promises being 'launched'.

Now if you don't use defer, and you use concatMap, I believe you should have all AJAX request started, and still the right ordering. So you could write :

.concatMap(function(page) {
  return $.get(page);

Relevant documentation: