I want to create a queue of all the http requests that are being made simultaneously, But the Catch is that we need to update request of next api after every success request, issue is the queue we create saves all the requests as a observables and i can not find a way to update the request from that observable
Request Queue Service
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpEventType } from '@angular/common/http';
import { BehaviorSubject, Observable, ReplaySubject } from 'rxjs';
import { tap, catchError, switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RequestQueueService {
public queue: ReplaySubject<any>[] = [];
updatedRespose = new BehaviorSubject<any>(null);
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const requestQueueItem$ = new ReplaySubject<any>();
const result$ = requestQueueItem$.pipe(
switchMap(() => next.handle(request).pipe(
tap(req => {
if (req.type == HttpEventType.Response) {
this.processNextRequest();
}
}),
catchError(err => {
this.processNextRequest();
throw err;
})
))
);
this.queue.push(requestQueueItem$);
if (this.queue.length <= 1) {
this.dispatchRequest();
}
return result$;
}
private processNextRequest(): void {
if (this.queue && this.queue.length > 0) {
this.queue.shift();
}
this.dispatchRequest();
}
private dispatchRequest(): void {
if (this.queue.length > 0) {
const nextSub$ = this.queue[0];
nextSub$.next();
nextSub$.complete();
}
}
}
Queue Interceptor
@Injectable()
export class QueueInterceptorService implements HttpInterceptor {
constructor(
private queueService: RequestQueueService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.queueService.intercept(request, next);
}
}
used this answer for queue
Thanks in advance