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

157
Views
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 answers
Answer question

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 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!