기본 콘텐츠로 건너뛰기

라벨이 cyclejs인 게시물 표시

cycle.js driver에 대한 정리.

cyclejs는 observable을 logic, subscribe를 effect로 각각 분리하고 서로 순환하는 구조인 full reactive framework 이다. 예를 들면 1초(1000ms)마다 스트림을 발산하는 text$는 매번 fold(reduce)하여 1씩 증가하고 "Second elapsed xx"로 map하는 text$=xs.periodic(1000)   .fold(prev=>prev+1,0)   .map(i=>`Second elapsed ${i}`) 를 logic. 이를 subscribe 하여 #app element의 텍스트로 넣는 것을 text$.subscrbie({   next: str => document.querySelector('#app').textContent = str }) 를 effect로 볼 수 있다. 이를 각각 함수로 구분하여 const sink = ()=> xs.periodic(1000)     .fold(prev=>prev+1,0)     .map(i=>`Second elapsed ${i}`); const domDriver = text$ => text$.subscribe({   next: str => document.querySelector('#app').textContent = str }); domDriver(sink); 이와 같이 재정의 할 수 있다. 같은  logic에 대해 DOM 렌더링과 log를 분리하려면 logDriver를 아래와 같이 추가하여 const logDriver = msg => console.log(msg); logDriver(sink); 하여도 마찬가지. subscribe한 객체의 observable만 있으면 DOM이건 console이건 canvas건 websocket이건 어느쪽이든 effect를 만들어 낼 수 있다. ...

Cycle.js 의 Driver에 대한 이야기

왜 이름이 Driver 인가 OS에서 외부하드웨어와 연결하는 소프트웨어를 Driver라고 하는데 외부로부터 영향(effect)를 주고 영향을 받는다는 점에서 아이디어를 얻음. DOM Driver Sink가 없는 형태의 Driver function WSDriver(/* no sinks */) {   return xs.create({     start: listener => {       this.connection = new WebSocket('ws://localhost:4000');       connection.onerror = (err) => {         listener.error(err)       }       connection.onmessage = (msg) => {         listener.next(msg)       }     },     stop: () => {       this.connection.close();     },   }); } websocket의 예 Driver 만드는 법 function myDriver(sink$, name /* optional */) 부터 시작. 다시 Sock(가짜 실시간 리얼타임 채널 API) 구현 // Establish a connection to the peer let sock = new Sock('unique-identifier-of-the-peer'); // Subscribe to messages received from the peer sock.onReceive(function (msg) ...