Angular 2+仅在更改时订阅observable

时间:2017-05-18 09:20:30

标签: angular observable angular2-observables behaviorsubject

所以这是场景。我有一个带有BehaviorSubject的用户服务和一个返回此BehaviorSubject的observable的方法。我的第二个文件是订阅observable的标题组件。 问题是..是否可以只订阅更改,或者我需要在this.userSubject.next(this.user)之前有一些逻辑吗?

这里有参考代码:

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

在这里

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

2 个答案:

答案 0 :(得分:6)

您可以使用distinctUntilChanged运算符(documentation):

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

这应该通过将每个发射值与前一个值进行比较来过滤它们,如果它不同,那么将调用订阅,否则不会。

答案 1 :(得分:0)

更新了新 Rxjs 版本的答案:使用 .pipe(distinctUntilChanged())

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