我希望在组合的最新可观察量中检测新的变化。两个原始的可观察流都是长期存在的,我想检测更改是否添加了新项目,或删除了组合最新可观察量中的项目,但我不确定如何将新的组合最新可观察值与更改前的旧值进行比较。
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)
});
目前,每次可观察量更改时,都会console.log('Combined$ ', friends)
运行此操作。但是我只想在添加或删除新项目时才运行它。
您可以通过
使用 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)
});