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?
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
async pipearea$!: 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>
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.