首页 > 解决方案 > RxJS。组合发射时间小于 1 秒的可观察对象

问题描述

有两个 observables 可以一起或单独发射:stream1stream2. stream2仅当触发时间少于 1 秒时,我才需要触发订阅stream1
有什么方法可以用 RxJS 实现吗?

标签: javascriptrxjsreactive-programmingrxjs-observablesrxjs-pipeable-operators

解决方案


您可以使用时间戳并withLatestFrom决定要发出哪些值在这里我只是过滤,以便只有满足您条件的值才能通过。

stream2.pipe(
  timestamp(),
  withLatestFrom(stream1.pipe(
    timestamp(),
    startWith({timestamp: 0, value: null})
  )),
  filter(([s2, s1]) => s2.timestamp - s1.timestamp < 1000),
  map(([s2, s1]) => ({
    stream1: s1.value,
    stream2: s2.value
  }))
);

推荐阅读