Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
How to ensure observables from different components are complete?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
      }
    })
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!