Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running async tasks in parallel

In RxJS, when you want to run http requests in sequence- you chain them. But I'm not clear on how can I run requests in parallel? I saw in the examples on http://reactive-extensions.github.io/learnrx/ that they use Observable.zip() to run 2 requests in parallel. But how would you run 5 requests in parallel? More specifically, how can I setup so that my function is called:

  • when all 5 complete?
  • when first complete?
like image 442
Pavle Lekic Avatar asked Sep 29 '22 14:09

Pavle Lekic


1 Answers

Use combineLatest or forkJoin!

// Assume you have an array of urls
const urls = [
  "twitter.com/puppies.json", 
  "google.com/puppies.json", 
  "facebook.com/puppies.json"
];

// Let's map these urls to Ajax Observables
const requests = urls.map(url => Rx.DOM.Ajax.getJSON(url))

// Now combine the result from each request into an observable
// Here's combineLatest:
const allThePuppies$ = Rx.Observable.combineLatest(...urls)
// Alternatively, here's forkJoin:
const allThePuppies$ = Rx.Observable.forkJoin(urls)


// When you subscribe to `allThePuppies$`, you'll kick off all your requests in parallel, and your response will contain an array with the results from each request:
allThePuppies$.subscribe(results => {
  const twitterPuppies, googlePuppies, facebookPuppies = results;
  // Do what you must with the respective responses
  // (Presumably in this example you'd show your users some adorable pics of puppies)
})

combineLatest takes in an arbitrary number of observables, and once each of them have emitted at least one value, it will emit an array of the latest value from each observable when any of those observables fires.

That's terribly abstract, though. For our purposes, we know that a handful of ajax requests will realistically only emit once. So, if we use combineLatest for a handful of ajax observables, we'd end up with an observable that emits an array of results from each of the ajax requests.

forkJoin is similar to combineLatest, but it only emits its array of responses once each of its constituent observables has completed.

like image 115
brettimus Avatar answered Oct 02 '22 16:10

brettimus