sources

现在,我们实现的 main() 函数只能接收 DOM source:

function main(DOMSource) {
  const click$ = DOMSource;
  return {
    DOM: click$
      .startWith(null)
      .flatMapLatest(() =>
        Rx.Observable.timer(0, 1000)
          .map(i => `Seconds Elapsed ${i}`)
      ),
    Log: Rx.Observable.timer(0, 2000)
      .map(i => 2 * i)
  };
}

实际环境中,读副作用 不只来自于 DOM,为此,我们需要:

  • 修改 main() 函数,使其能够接收不同类型的 source。
  • 修改 run() 函数,代理各个类型的 source。
function main(sources) {
  const click$ = sources.DOM;
  return {
    DOM: click$
      .startWith(null)
      .flatMapLatest(() =>
        Rx.Observable.timer(0, 1000)
          .map(i => `Seconds Elapsed ${i}`)
      ),
    Log: Rx.Observable.timer(0, 2000)
      .map(i => 2 * i)
  };
}

function run(main, drivers) {
  const proxySources = {};
  Object.keys(drivers).forEach(key => {
    proxySources[key] = new Rx.Subject();
  });
  const sink = main(proxySources);
  Object.keys(drivers).forEach(key => {
    const source = drivers[key](sink[key]);
    source && source.subscribe(x => proxySources[key].onNext(x));
  });
}

查看示例

当然,Cycle.js 提供的 run() 函数更加健壮和通用:

<script src="https://rawgit.com/cyclejs/cycle-core/v6.0.0/dist/cycle.js"></script>
Cycle.run(main, drivers);

查看示例

results matching ""

    No results matching ""