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);
});
}
Updated answer for the new Rxjs version: use .pipe(distinctUntilChanged())
ngOnInit() {
this.userService.keepUpdated();
this.userService.userStream()
.pipe(distinctUntilChanged())
.subscribe(user => {
console.log(user);
});
}