danday74
danday74

Reputation: 57225

RxJS batch HTTP requests in Angular

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?

Upvotes: 3

Views: 3297

Answers (2)

micronyks
micronyks

Reputation: 55443

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

Upvotes: 2

bubbles
bubbles

Reputation: 2727

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

Upvotes: 1

Related Questions