Search code examples
angularrxjsobservableangular14

How to limit the number of simultaneous http requests, using Angular?


Let's assume I'm uploading 100 images, so my Angular frontend has to make 100 API-calls. Yet due to backend restrictions, I would like to have a maximum of 5 simultaneous API requests at any given point of time. Whenever one of the http-requests in the queue is completed another request should be added and executed.

How can I achieve this?


Solution

  • The second parameter of mergeMap corresponds to the maximum number of concurrent API calls. Setting this parameter to 5 means that at any given time, only 5 API requests will be executed, and as soon as one request finishes, another one will be initiated.

    Check my Stackblitz example or have a look at the code below:

    import { mergeMap, of } from 'rxjs';
    
    // Set max. number of simultaneous requests:
    const numberOfSimultaneousRequests = 5;
    
    // Add 50 observables that will execute the API-requests:
    const allApiCalls = Array.from({ length: 50 }, (_, i) => this.makeApiCall(i));
    
    of(...allApiCalls)
      .pipe(mergeMap((apiCall) => apiCall, numberOfSimultaneousRequests))
      .subscribe((response) => {
        console.log(response);
      });
    }
    
    mockApiCall(value: number): Observable<number> {
      return of(value).pipe(delay(1000));
    }