I am faced with a situation where multiple components on a page are utilizing observables to fetch API data. I have implemented a loading service that is responsible for displaying a loader from the time the first observable is initiated until the last one is completed.
Here is an example of the loading service:
private _loading = new BehaviorSubject<boolean>(false);
readonly loading$ = this._loading.asObservable();
showUntilLoadingComplete<T>(observable$: Observable<T>): Observable<T> {
return of(null).pipe(
tap(_ => this._loading.next(true)),
concatMap(_ => observable$),
finalize(() => this._loading.next(false))
);
}
The components utilize the loading service in the following manner:
this.loadingService.showUntilLoadingComplete(someObservable$)
.subscribe(data=> {
// perform actions
});
One issue that arises is that when the first observable completes, the behavior subject switches to false, causing the loader to stop showing. One potential solution I have considered is creating another behavior subject to store an array of active observables, removing them once they are finalized, and then monitoring the length of the array to determine when to turn off the loader. However, this approach does not seem optimal, so I am seeking suggestions from others.