Gabriel
Gabriel

Reputation: 821

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);
    });
}

Upvotes: 4

Views: 11547

Answers (2)

Nadhir Falta
Nadhir Falta

Reputation: 5257

Updated answer for the new Rxjs version: use .pipe(distinctUntilChanged())

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

Upvotes: 1

Supamiu
Supamiu

Reputation: 8731

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.

Upvotes: 8

Related Questions