Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda