I'm having trouble with RxJS and the correct way to handle an array of request. Let's say I have an array of about 50 requests as follows:
let requestCounter = 0;
function makeRequest(timeToDelay) {
return of('Request Complete!').pipe(delay(timeToDelay));
}
const requestArray = []
for(let i=0;i<25;i++){
requestArray.push(makeRequest(3000)); //3 seconds request
requestArray.push(makeRequest(1000)); //1 second request
}
My goal is to:
- Launch the requests in parallel
- Only 5 can run a the same moment
- When a request is done, the next in the array starts
- When a request is done(success or error), I need to increment my variable 'requestCounter' by one (requestCounter++)
- When my last request in the queue is done, I need to subscribe to this event and handle an array resulting of every requests result
So far the closest I've been to do this is by following the response in this post:
RxJS parallel queue with concurrent workers?
The thing is that I'm discovering RxJS and the exemple is way too complicated for me and I can't find how to handle the counter for each request.
Hope you can help me. (Sorry for the broken english, it is not my native language)
Edit: Final solution looks like this:
forkJoinConcurrent<T>(
observables: Observable<T>[],
concurrent: number
): Observable<T[]> {
return from(observables).pipe(
mergeMap((outerValue, outerIndex) => outerValue.pipe(
tap(// my code ),
last(),
catchError(error => of(error)),
map((innerValue, innerIndex) => ({index: outerIndex, value: innerValue})),
), concurrent),
toArray(),
map(a => (a.sort((l, r) => l.index - r.index).map(e => e.value))),
);
}