javascript - 当第二个 observable 发生变化时,combineLatest 没有发射?

标签 javascript typescript rxjs

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

https://codesandbox.io/s/modest-vaughan-1t9k0

关于javascript - 当第二个 observable 发生变化时,combineLatest 没有发射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58887494/

相关文章:

visual-studio-2013 - 如何在 VS2013 中强制 TypeScript 重新编译?

angular - 使用主题和代理传递数据

javascript - 从 Rails 到 AngularJS 的安全响应

javascript - 如何循环枚举值以在单选按钮中显示?

javascript - 循环和变量中的 Event.observe

javascript - 为什么我在这个简单的组件中遇到 Angular 编译错误

javascript - 如何通过使用 takeUntil 的多个条件来停止订阅

unit-testing - 对使用 RxJs 主题的 Angular2 服务进行单元测试

javascript - 如何开发一个搜索选项以在 MVC View 表中按列搜索

javascript - Vue v-for 在新文本区域上自动对焦