我有两个独立的流,它们在 combineLatest 中聚集在一起,如下所示:
const programState$ = Rx.Observable.combineLatest(
high$, low$,
(high, low) => {
return program(high, low);
});
这工作正常而且花花公子,但我也希望能够将 high$ 和 low$ 重置为它们的初始状态并且只启动程序一次。这些看起来像下面这样:
const high$ = initialDataBranchOne$.merge(interactiveHigh$);
const low$ = initialDataBranchTwo$.merge(interactiveLow$);
这两个都来自从事件触发的初始数据流。当程序正常运行时,combineLatest 运行良好。如何在触发 initialData fromEvent 时获得相同的结果?现在程序运行了两次。
最佳答案
我们可以将 high
和 low
属性存储在同一个对象中。然后我们可以在各种事件进入时执行扫描
以更新此状态:
// Define your default high/low values
const defaultHighLow = /** **/;
// Different types of updates/actions
const highUpdate$ = high$.map(high => ({ high, type: 'UPDATE HIGH' }));
const lowUpdate$ = low$.map(low => ({ low, type: 'UPDATE LOW' }));
const resetUpdate$ = reset$.map(high => ({ type: 'RESET' }));
// Merge all the different types of actions to single stream
const update$ = Rx.Observable.merge(highUpdate$, lowUpdate$, resetUpdate$);
// Scan over these updates to modify the high/low values
const highLowState$ = update$.scan((state, update) => {
if (update.type === 'UPDATE HIGH') {
return { ...state, high: update.high };
}
if (update.type === 'UPDATE LOW') {
return { ...state, low: update.low };
}
// Return defaultHighLow if reset update is triggered
if (update.type === 'RESET') {
return defaultHighLow;
}
// Return state by default
return state;
}, defaultHighLow).startWith(defaultHighLow);
最后我们可以像以前一样导出程序状态:
const programState$ = highLowState$.map(hl => program(hl.high, hl.low));
关于javascript - rxjs:重置为流并且只获得一个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336255/