检测zipped.Observable中的新更改

时间:2018-03-06 18:25:12

标签: angular rxjs observable

我希望检测CombinedLatest Observable中的新变化。两个原始的Observable流都是长寿的,我想检测更改是否添加了一个新项,或者删除了CombinedLatest Observable中的一个项,但我不确定如何将新的combinedLatest可观察值与改变前的旧的。

      this.friendsOnMap$ = combineLatest(this.friendsOnlyPeople$, this.friends$)
  .pipe(map(([friendsOnlyPeople, friends]) => friendsOnlyPeople
  .map(this.checkIfFriend(friends))))
  .map(friend => {
    return friend.filter(friend => friend.isFriend == true);
  })
  .subscribe(friends => {
    console.log('Combined$ ', friends)
  });

目前,每次Observable更改时都会运行console.log('Combined$ ', friends)。但是我想只在添加或删除新项目时运行它。

1 个答案:

答案 0 :(得分:0)

如果没有添加或删除任何朋友,您可以使用distinctUntilChanged并传递自定义compare函数来实现此目的...在您的情况下返回true

this.friendsOnMap$ = combineLatest(this.friendsOnlyPeople$, this.friends$).pipe(
  map(([friendsOnlyPeople, friends]) => friendsOnlyPeople.map(this.checkIfFriend(friends))),
  map((friends: Friend[]) => friends.filter(friend => friend.isFriend == true)),
  distinctUntilChanged((p: Friend[], q: Friend[]) => {
    // return true if p and q are the same set of identities
    ...
  })
).subscribe(friends => {
  console.log('Combined$ ', friends)
});
相关问题