rxjs:重置为流,只得到一个输出

rxjs: reset to streams and only get one out put

本文关键字:输出 一个 rxjs      更新时间:2023-10-07

我有两个单独的流,它们组合在一起。最新内容如下:

const programState$ = Rx.Observable.combineLatest(
    high$, low$,
    (high, low) => {
        return program(high, low);
    });

这很好用,但我也希望能够将高$和低$重置为初始状态,并且只启动一次程序。这些看起来如下:

const high$ = initialDataBranchOne$.merge(interactiveHigh$);
const low$ = initialDataBranchTwo$.merge(interactiveLow$);

这两个都来自initialData流,该流是从Event中激发的。当程序正常运行时,combineLatest工作得很好。当initialData from Event被激发时,我如何才能获得相同的结果?现在程序运行两次。

我们可以将highlow属性存储在同一个对象中。然后,我们可以在各种事件进入时执行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));