[Cycle.js] Generalizing run() function for more types of sources

Our application was able to produce write effects, through sinks, and was able to receive read effects, through the DOM sources. However, the main function only gets the DOMSource as input. This lessons shows how we can generalize main to receive an object of sources, containing all kinds of read effects that we can use.

 

Code to be chagned:

复制代码
function run(mainFn, drivers) {
  const proxyDOMSource = new Rx.Subject();
  const sinks = mainFn(proxyDOMSource);
  const DOMSource = drivers.DOM(sinks.DOM);
  DOMSource.subscribe(click => proxyDOMSource.onNext(click));
//   Object.keys(drivers).forEach(key => {
//     drivers[key](sinks[key]);
//   });
}
复制代码

 

This is hard code now, make it more fixable:

复制代码
function run(mainFn, drivers) {

  const proxySource = {};

  //For each driver, we need to proxySource
  Object.keys(drivers).forEach( (key)=>{
    proxySource[key] =  new Rx.Subject();
  } );

  //Get sinks (output effect)
  const sinks = mainFn(proxySource);

  Object.keys(drivers).forEach( (key)=>{
    //for each drive, create a source for that
    const Source = drivers[key](sinks[key]);
    
    Source.subscribe( x => proxySource[key].onNext(x) );
  } );
}
复制代码

 

---------------------

Code:

复制代码
// Logic (functional)
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),
  };
}

const drivers = {
  DOM: DOMDriver,
  Log: consoleLogDriver,
}

// bProxy = ...
// a = f(bProxy)
// b = g(a)
// bProxy.imitate(b)

function run(mainFn, drivers) {

  const proxySource = {};
  Object.keys(drivers).forEach( (key)=>{
    proxySource[key] =  new Rx.Subject();
  } );
  const sinks = mainFn(proxySource);
  Object.keys(drivers).forEach( (key)=>{
    const Source = drivers[key](sinks[key]);
    Source.subscribe( x => proxySource[key].onNext(x) );
  } );
}

run(main, drivers);

// source: input (read) effects
// sink: output (write) effects



// Effects (imperative)
function DOMDriver(text$) {
  text$.subscribe(text => {
    const container = document.querySelector('#app');
    container.textContent = text;
  });
  const DOMSource = Rx.Observable.fromEvent(document, 'click');
  return DOMSource;
}

function consoleLogDriver(msg$) {
  msg$.subscribe(msg => console.log(msg));
}
复制代码

 

posted @   Zhentiw  阅读(147)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示