Angular 2+ subscribe to observable on change only

Gabriel picture Gabriel · May 18, 2017 · Viewed 8k times · Source

So here is the scenario. I have a user service with a BehaviorSubject and a method returning an observable of this BehaviorSubject. My second file is the header component which subscribes to the observable. The question is.. Is it possible to subscribe on changes only or do I need to have some logic on before the this.userSubject.next(this.user)?

For reference here is the code:

// user.service.ts
user: User;
private userSubject = new BehaviorSubject<User>(new User({}));

keepUpdated = () => {
  this.tokenService.tokenStream()
    .subscribe(token => {
      this.user.update(token);
      this.userSubject.next(this.user);
    });
}

And here

// header.component.ts
ngOnInit() {
  this.userService.keepUpdated();
  this.userService.userStream()
    .subscribe(user => {
      // Here is the problem. This console.log gets called everytime userSubject.next(this.user) send something. I would like it only only to be called if the user is different from the previous one.
      console.log(user);
    });
}

Answer

Supamiu picture Supamiu · May 18, 2017

You can use distinctUntilChanged operator (documentation):

ngOnInit() {
  this.userService.keepUpdated();
  this.userService.userStream()
    .distinctUntilChanged()
    .subscribe(user => {
      console.log(user);
    });
}

This should filter each emitted value by comparing it with the previous one, if it is different, then the subscription will be called, else no.