javascript - RxJS:延迟可观察项的生成

标签 javascript reactive-programming rxjs

假设我有一个可观察的对象,它生成从 09 的元素。我想要一个新的可观察对象,它仅在 7 之后发出 3 。我相信它应该看起来像这样:

// INPUT:  0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
// OUTPUT: 0 - 1 - 2 ----- 4 - 5 - 6 - 7 - 3 - 8 - 9 

let source = Rx.Observable.range(0, 10).XXX([
    item => item === 3,
    item => item === 7
]);

RxJS是否包含这样的XXX方法?

最佳答案

我不知道存在什么方法,但是,我们可以尝试解决一些问题。让我们将底层可观察量分成两个流;一个满足我们的谓词(即 x => x === 3),另一个值不满足该谓词:

const item$ = Rx.Observable.range(0, 10);
const predicate = x => x === 3;

// Split our underlying stream into two Observables; one where each value
// will equal three, and the other where each value is not three.
const [ three$, notThree$ ] = item$.partition(predicate);

我们可以创建一个每当数字 7 出现时就会发出的流:

const seven$ = notThree$.filter(x => x === 7);

现在,让我们创建两个流来表示 7 发出之前和之后的基础数据

const beforeSeven$ = notThree$.takeUntil(seven$);
const afterSeven$ = notThree$.skipUntil(seven$);

最后,我们可以组合这些流以获得所需的效果。我们基本上在 beforeSeven$ 流结束后立即连接 afterSeven$ 和 Three$ 流:

const result$ = beforeSeven$.concat(three$.merge(afterSeven$);

这是一个 jsfiddle,console.log 的结果是:https://jsfiddle.net/cbelden/ppjmxww1/

关于javascript - RxJS:延迟可观察项的生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986081/

相关文章:

php - 在声明变量之前/之后运行脚本?

javascript - 如果不使用新的 if 语句,我将如何比较特定值?

javascript - RxJS - 收集异步操作结果

java - 如何在准备就绪时使用响应式(Reactive) Flux/Mono 将消息推送到上游,而不是间隔轮询状态?

javascript - 使用 Redux-Observable 的通用 Epic

javascript - 上下文菜单有时会消失

javascript - 根据用户输入设置选中的复选框

javascript - RxJs:组合两个可观察量 - 从第一个观察到的所有,但不是从第二个观察到的全部

angular - 为什么嵌套订阅不好?

javascript - 为什么 throttle 不工作?