在 RxJS 中,当您想要按顺序运行 http 请求时,您可以将它们链接起来。但我不清楚如何并行运行请求?我在例子中看到http://reactive-extensions.github.io/learnrx/ http://reactive-extensions.github.io/learnrx/他们使用 Observable.zip() 并行运行 2 个请求。但是如何并行运行 5 个请求呢?
更具体地说,如何设置以便调用我的函数:
Use 结合最新 http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-combineLatest or forkJoin http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-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
接受任意数量的 observable,一旦每个 observable 发出至少一个值,当其中任何一个 observable 触发时,它将发出每个 observable 的最新值的数组。
但这是非常抽象的。出于我们的目的,我们知道少数 ajax 请求实际上只会发出一次。所以,如果我们使用combineLatest
对于少数 ajax observables,我们最终会得到一个 observable,它从每个 ajax 请求中发出一组结果。
forkJoin
类似于combineLatest
,但只有在其每个组成的可观察量完成后,它才会发出其响应数组。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)