I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization after all requests are complete to execute additional code.
I have explored various suggestions from:
Limit number of requests at a time with RxJS
How to limit the concurrency of flatMap?
Fire async request in parallel but get result in order using rxjs
and more... I even attempted to create my own operators.
However, either the solutions provided do not align with my specific requirements or I am struggling to integrate them seamlessly into my existing codebase.
This is the current state of my implementation:
for (const obj of objects) {
this.myService.updateObject(obj).subscribe(value => {
this.anotherService.set(obj);
});
}
EDIT 1: I believe progress is being made! Utilizing the insights from Julius and pschild, I have managed to control the request concurrency. However, only the first batch of 4 requests is triggered while subsequent batches remain inactive. Here's the updated snippet:
const concurrentRequests = 4;
from(objects)
.pipe(
mergeMap(obj => this.myService.updateObject(obj), concurrentRequests),
tap(result => this.anotherService.set(result))
).subscribe();
Is there an issue with the way I'm handling the subscribe()
method?
By the way: The use of mergeMap
with the resultSelector
parameter has been deprecated, hence why I omitted it. Also, the reference to obj
within the mergeMap
function is not accessible in the tap
, necessitating the use of the parameter passed to tap
.
EDIT 2:
Ensure that your observers complete! (This lesson cost me an entire day)