Search code examples
angulartypescriptrxjsbehaviorsubject

Correctly Mutating BehaviorSubject Object


This is a part of my Angular Service:

private user = new User();
private user$ = new BehaviorSubject < User > (this.user);

public getUser(): Observable < User > {
  return this.user$.asObservable().share();
}

public setUser(user: User) {
  this.user$.next(user);
}

What's the proper way to change only one field/property of user and reemitting the whole object again?


Solution

  • You can model your state as scan of events. Each event will generate new state from previous (without mutation).

    Take a look at this example - RxJS observe an object