Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ subscribe to observable on change only

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);
    });
}
like image 239
Gabriel Avatar asked Aug 31 '25 01:08

Gabriel


1 Answers

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.

like image 88
Supamiu Avatar answered Sep 03 '25 10:09

Supamiu