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

310
Visualizações
Angular listen on subscription start of rxjs observable?

Is there a way to detect the start of the subcription of a rxjs observable within the pipe?

I want to trigger a loading indicator when a http observable (destroyed when respone has been finalized) get subscribed.

Or do I have to create a wrapper observable for this action?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

It depends on what RxJS version you're using. With RxJS < 7.3 you can use defer():

defer(() => {
  loadingFlag = true;
  return this.http.doyourrequest().pipe(
    finalize(() => loadingFlag = false),
  );
});

Since RxJS >= 7.3 you can use new event handlers for tap():

this.http.doyourrequest().pipe(
  tap({
    subscribe: () => loadingFlag = true,
    finalize: () => loadingFlag = false,
  }),
);
over 4 years ago · Santiago Trujillo Relatório

0

since every subscription to http observable causes new http call it is safe to set such flag outside of the pipe, at least it is how I do it.

getSomeData(){
  loadingFlag=true;
  return this.http.doyourrequest().pipe(finalize(()=>loadingFlag=false));
}

if you really want to go trough sub count(which is always down to 0 after every request due to finalizztion of http obs) check the implementation of refCount() and share() operators which internally counts the subscribers

Edit:

You can encapsulate setting of the flag using dummy observable as an entry point eg

getSomeData(){
  return of(null).pipe(
      tap(()=>loadingFlag=true),
      switchMapTo(this.http.doyourrequest()),
      finalize(()=>loadingFlag=false)
  )
}
over 4 years ago · Santiago Trujillo Relatório

0

Instead of setting some indicator as a side effect in your stream, try creating an observable that returns the state of your request.

readonly makeRequestSubject = new Subject<RequestParams>();
readonly request$ = makeRequestSubject.pipe(
  switchMap(params => this.doRequest(params).pipe(
    map(result => ({ params, result,  state: 'complete' })),
    catchError(error => ({ error, params, state: 'error' }))
    startWith({ params, state: 'loading' })
  ),
  startWith({ state: 'notstarted' }),
  shareReplay(1)
);
readonly isLoading$ = this.request.pipe(map(x => x === 'loading'), distinctUntilChanged());
readonly results$ = this.request.pipe(map(x => x === 'complete' ? x.results : []));
  1. You could return an observable from a method and use it like an overweight promise, or you could have a single field that contains the stream, and all dependents could just subscribe and unsubscribe to it when they want. next() on makeRequestSubject gets called every time you need to make a new request.
  2. The outer startWith should emit first. This is optional, but might be useful in some ui scenarios, such as showing a message with instructions if no requests have been made.
  3. The request is initiated in a switchMap so succcessive calls will interrupt the prior ones if they're not already complete.
  4. The inner startWith operator will emit first unless the request is instantaneous.
  5. catchError illustrates another typical use case beyond settings a loading indicator.
  6. You could subscribe to request$ directly, or use isLoading$ and results$**. I typically try to avoid creating extra observables, and just make sure the model on my component in a master stream matches up with my ui bindings.
  7. Params were just included because they might be useful in the ui.
over 4 years ago · Santiago Trujillo 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