Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda