[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));
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值