Home > other >  How to ensure observables from different components are complete?
How to ensure observables from different components are complete?

Time:03-29

I have a number of components on a page, which all use observables to get API data. I pass these observables to a loading service, which I want to display a loader from when the first observable is passed until the last one has finalised.

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))
  );
}

My components then call loading service like so:

this.loadingService.showUntilLoadingComplete(someObservable$)
    .subscribe(data=> {
       // do stuff
    });

However, due to the first observable finalising, the behaviour subject gets passed false and this in turn stops the loader from showing. I have considered creating another behaviour subject to store an array of the active observables, and remove them from here once finalised, and then subscribing to that and setting the loader off once the array has no length. But this doesn't seem like a great solution, so I am looking for others input.

CodePudding user response:

Since you're depending on the same loading$ Observable in a singleton service, then you can add another property to reflect the active number of calls, then turn the loading off only if there is no other active call.

Try something like the following:

private _active: number = 0;
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);
      this._active  ;
    }),
    concatMap((_) => observable$),
    finalize(() => {
      this._active--;
      if (!this._active) {
        this._loading.next(false);
      }
    })
  );
}
  • Related