问题描述:
当使用BehaviorSubject观察一个对象时,每次该对象的任何属性值发生更改都会触发可观察者的多次调用。
可以使用RxJS的combineLatest运算符将可观察者的多个值合并到一个单独的可观察者中,并将订阅该单一可观察者。在此示例代码中,我们的可观察者是BehaviorSubject,并且我们通过在switchMap中调用combineLatest运算符来解决多次触发问题。
import { BehaviorSubject, combineLatest } from 'rxjs';
const myObject = {
foo: 'Hello',
bar: 'World'
};
const myObjectSubject = new BehaviorSubject(myObject);
// 所有数据更改的通知都通过对myObjectSubject调用“next”方法来触发
myObjectSubject.next({
...myObjectSubject.value,
baz: '!!!'
});
myObjectSubject.pipe(
switchMap(obj =>
combineLatest(
Object.keys(obj).map(key => obj[key])
)
)
).subscribe(data => {
console.log(data);
});