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

166
Visualizações
RxJs: Update observables inside a subscription correctly

I wondered how to update a observable inside a subscription without triggering to many events.

In this example I subscribe to area: Observable<Area>, if the area changes I'd like to update the theme: Observable<Theme>. distinctUntilChanged() should do that the subscription is only triggered if the value has changed, but everytime the area gets updated, the amount of theme updates increases by one.

  observeArea(): void {
    this.area
    .pipe(distinctUntilChanged()) 
    .subscribe(area => {
      this.themeService.updateTheme({primaryColor: area.color}); // should happen only once per area change
    })
  }

Is there any "correct" way of doing this, without triggering endless theme updates?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think the problem might be with the way you are updating the theme.

If you are trying to update the theme by calling observeArea() method.

Every time you call the method a new subscription will be created. Event will be passed to every subscription. So each time you call the method one subscription will be increasing.

Solution

  1. Use an async pipe
area$!: Observable<any>;
observeArea(): void {
  this.area$ = this.area
  .pipe(
    distinctUntilChanged(),
    tap(area => this.themeService.updateTheme({primaryColor: area.color});)
   )
}

and in html use area$ | async to subscribe. example:

<ng-container *ngIf="area$ | async">...</ng-container>
  1. Else you should unsubscribe every time your subscription completes
observeArea(): void {
    const sub = this.area
    .pipe(distinctUntilChanged()) 
    .subscribe(area => {
      this.themeService.updateTheme({primaryColor: area.color});
      sub.unsubscribe();
    })
  }

Better to use async pipe.

I believe this solves your issue.

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