This is a stackblitz demo of the below code .
有两个可观察对象 - active$
- collection$
:
const central:EStore<Todo> = new EStore();
const collection:EStore<Todo> = new EStore();
const active$ = central.observeActive();
const collection$ = collection.observe();
当 collection$
通知时,记录在这个语句中:
collection$.subscribe(v=>console.log('Todo added to collection'));
此combineLatest
函数不会触发:
const isActiveTodoInCollection$:Observable<boolean> =
combineLatest(active$,
collection$,
(a, c)=>{
console.log("Firing");
if (getMapValue(central.active)) {
return collection.containsById(getMapValue(central.active));
}
return false;
});
但是,如果我们让 active$
observable 发出通知,isActiveTodoInCollection$
observable 就会触发。
为什么当 collection$
observable 通知时它不触发?
另一件奇怪的事情是当 collection$
通知时,这将产生一个日志语句:
const t$ = combineLatest(collection$, (c)=>console.log("collection$ performing a notification"));
t$.subscribe();
但是如果我们将 active$
observable 添加到参数中,它就会停止通知。就好像 active$
必须先通知 ...
最佳答案
combineLatest 仅在每个可观察对象至少发出一次值时才起作用。
central.post(todo) 并没有真正完成,因为在您的情况下,observeActive() 仅在调用 central.addActive(todo) 时才真正观察到,因此没有任何东西可以组合。
示例来说明问题,在下面的代码中注释两个 $ 并取消注释以下行,您将看到不同之处
import { combineLatest, Observable } from "rxjs";
const one$ = new Observable(subscriber => {
setTimeout(() => {
console.log("set");
subscriber.next(42);
}, 1000);
});
const two$ = new Observable(subscriber => {});
// comment above two$ and uncomment this
/*const two$ = new Observable(subscriber => {
subscriber.next(56);
});*/
combineLatest(one$, two$).subscribe(([one, two]) => {
console.log(
` One Latest: ${one},
Two Latest: ${two}`
);
});
关于javascript - 当第二个 observable 发生变化时,combineLatest 没有发射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58887494/