Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS batch HTTP requests in Angular

Tags:

angular

rxjs

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?

like image 761
danday74 Avatar asked Feb 04 '26 16:02

danday74


2 Answers

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

like image 53
Nikhil Shah Avatar answered Feb 06 '26 06:02

Nikhil Shah


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

like image 45
bubbles Avatar answered Feb 06 '26 05:02

bubbles