我有两个独立的流,它们在combineLatest中汇集在一起,如下所示:
const programState$ = Rx.Observable.combineLatest(
high$, low$,
(high, low) => {
return program(high, low);
});
这样可以正常工作,但我也希望能够将高$和低$重置为初始状态,并且只启动程序一次。那些看起来如下:
const high$ = initialDataBranchOne$.merge(interactiveHigh$);
const low$ = initialDataBranchTwo$.merge(interactiveLow$);
这两个都来自从事件触发的initialData流。虽然程序运行正常,但combineLatest运行良好。当触发initialData fromEvent时,如何获得相同的结果?现在程序运行两次。
答案 0 :(得分:2)
我们可以将high
和low
属性存储在同一个对象中。然后,当各种事件进入以更新此状态时,我们可以执行scan
:
// 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));