0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks , your answer is great, but I would know how to do this If I don't know the range number ?
I don't know what is your use-case exactly but in your example you used for so I guess you know the range beforehand. If not, you can use Subject and push ids (or whatever) and mergeMap() will take care of the concurrency requests.
Yes I have not well described my case. I have a ui list that when click in get all will triggeran event on each event , and this event will call the http request
Then it sounds like you can use that as a source Observable instead of range() or an intermediate subject.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.