I have an array of arrays like this:
const mynums = [[1,2], [3,4]] // this array may contain any number of integer arrays
Using this I want to make the following HTTP requests:
http://myserver.com/resource/1 // 2 requests made simultaneously
http://myserver.com/resource/2
http://myserver.com/resource/3 // 2 requests made simultaneously but only after first 2 complete
http://myserver.com/resource/4
I know I can use forkJoin like so:
forkJoin([
this.http.get('http://myserver.com/resource/1')
this.http.get('http://myserver.com/resource/2')
]).subscribe(
(responses) => {
console.log(responses[0])
console.log(responses[1])
}
)
But how would I do this to batch HTTP requests to accommodate for the mynums array, which is of variable length and to ensure that the first batch of requests completes before the 2nd batch of requests is made? and allow for a 3rd or 4th batch also or N batches?
You can use concatMap & forkJoin to make other batch request once first batch gets over.
from(mynums).pipe(
concatMap (x=> {
return forkJoin(x.map(t=>{
return this.http.get(`http://myserver.com/resource/${t}`)
}))
})
).subscribe(console.log)
DEMO with batch requests
try this:
source = from([[1,2], [3,4]]);
source
.pipe(
map(idies => idies.map(id => "https://jsonplaceholder.typicode.com/todos/" + id)),
concatMap(urls => forkJoin(...urls.map(url => this.http.get(url))))
)
.subscribe(x => console.log(x))
whole code here
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