Home > Enterprise >  Combine multiple requests and subscribe sequentially with rxjs
Combine multiple requests and subscribe sequentially with rxjs

Time:02-26

I have a loop that sends x http requests.

In some cases user can send a so many requests and that could affect server performances.

I would like to convert existing logic and be able ho manage max requests number.

Sample code

for( let i; i<x; i   ) {
  this.subs= this.globalService.getData(formData, id).subscribe(data => {...}
}

How can I authorise triger only if the number of requests is < 10 for example otherwise wait for api response and check if current observers is less than 10 ?

It's important to subscribe sequentially and not send an array of data to not change code logic inside subscription.

CodePudding user response:

Probably the easiest way is using mergeMap() with an optional concurrency option.

range(x)
  .pipe(
    mergeMap(i =>  this.globalService.getData(formData, i), 10),
  )
  .subscribe();

This way you can make mergeMap() to perform at most 10 concurrent requests.

  • Related