Skip to content

Instantly share code, notes, and snippets.

@oriSomething
Last active October 12, 2016 18:51
Show Gist options
  • Save oriSomething/d86b21b960a5e3805ec7359468566333 to your computer and use it in GitHub Desktop.
Save oriSomething/d86b21b960a5e3805ec7359468566333 to your computer and use it in GitHub Desktop.
Mini-CycleJS with RxJS
import Rx from "rxjs/Rx";
import cycleRun from "./mini-cycle";
function loggerDriver(source$) {
source$.subscribe((text) => console.log(text));
return Rx.Observable.empty();
}
function main() {
return {
logger: Rx.Observable.of("hello"),
};
}
cycleRun(main, {
logger: loggerDriver,
});
import Rx from "rxjs/Rx";
/**
* @param {function(Object):Object} fn
* @param {Object.<string, Observable>} drivers
*/
export default function cycleRun(fn, drivers) {
/** @type {Object.<string, Subject>} */
const sinksSubjects = {};
/** @type {Object.<string, Observable>} */
const sources = {};
objectForEach(drivers, (driver, key) => {
const sinkSubject = new Rx.Subject();
const sink$ = sinkSubject.asObservable();
sinksSubjects[key] = sinkSubject;
sources[key] = driver(sink$);
});
/** @type {Object.<string, Observable>} */
const sinks$$ = fn(sources);
objectForEach(sinks$$, (sink$, key) => {
const sinkSubject = sinksSubjects[key];
sink$.subscribe(sinkSubject);
});
}
export default function objectForEach(obj, fn) {
if (obj != null) {
Object.keys(obj)
.forEach((key) => {
fn(obj[key], key, obj);
});
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment