Suppose I have 10 urls, and I wish to make an HTTP request for each one of them.
I could create an observable of the URLs, then .flatMap()
the requests for each one of them, and then .subscribe
for the results. But that would make all of the requests at once.
Is there a way to impose a limit to the number of requests to a fixed number, in order not to overload the server
pipe through mergeMap with your parallel limit as 2nd parameter
const MAX_PARALLEL_QUERIES = 3;
let allResults = [];
let observables = [] // fill with observables
from(observables)
.pipe(mergeMap(observable => observable, MAX_PARALLEL_QUERIES))
.subscribe(
partialResults => {
allResults = allResults.concat(partialResults);
},
err => {
// handle error
},
() => {
// get here when all obserable has returned
allResults.forEach(result=> {
// do what you want
});
}
);
It's 2018, rxjs 5 is here and this is how I solved it
urls$
.mergeMap((url) => request({ url }), null, 10)
.subscribe()
mergeMap
(aka flatMap
) already takes the "max concurrency" as its 3rd parameter (see the docs)
Btw. I am using universal-rxjs-ajax (the request
) for node compatibility, but it should work the same with Observable.ajax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With