Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Created October 5, 2015 04:45
Show Gist options
  • Save chrisirhc/dbb5b7bfaf922bc8ccef to your computer and use it in GitHub Desktop.
Save chrisirhc/dbb5b7bfaf922bc8ccef to your computer and use it in GitHub Desktop.
rx-interdependency-experiment
var Rx = require('rx');
var clone = require('lodash.clone');
var isequal = require('lodash.isequal');
var Config = new MutableSubject({a: null});
var Options = new MutableSubject({});
function MutableSubject(name, obj) {
var behaviorSubject = new Rx.BehaviorSubject(obj);
var mutableSubject = function (val, done) {
if (arguments.length) {
return setImmediate(function () {
behaviorSubject.onNext(val);
if (done) {
done();
}
}, this);
}
return behaviorSubject.getValue();
};
mutableSubject._subject = behaviorSubject;
return mutableSubject;
}
function changeConfig(key, value) {
var newConfig = clone(Config());
newConfig[key] = value;
Config(newConfig);
}
function getOptions(config) {
var options = {};
for (var i in config) {
var options;
var firstChar = i.charAt(0);
options[i] = [firstChar, firstChar + firstChar];
}
return options;
}
var uniqueConfig = Config._subject.distinctUntilChanged(null, isequal);
uniqueConfig
.subscribe(function (config) {
// Whenever config changes, update options
var newOptions = getOptions(config);
Options(newOptions);
});
var uniqueOptions = Options._subject.distinctUntilChanged(null, isequal);
Rx.Observable.combineLatest(uniqueOptions, uniqueConfig)
.filter(function containsEmptyOptions(optionsAndConfig) {
// Whenever options change, and it's unique, get latest from config,
// check if there are any missing options
var config = optionsAndConfig[1];
var options = optionsAndConfig[0];
for (var i in options) {
if (!config[i]) {
return true;
}
}
return false;
})
.subscribe(function fillInDefaults(optionsAndConfig) {
// If there are missing options, fill it up.
var newConfig = clone(optionsAndConfig[1]);
var options = optionsAndConfig[0];
for (var i in options) {
if (!newConfig[i]) {
newConfig[i] = options[i][0];
}
}
Config(newConfig);
});
function showState() {
console.log(Config(), Options());
}
module.exports = {
changeConfig: changeConfig,
showState: showState
};
{
"name": "rx-interdependency-experiment",
"version": "0.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"lodash.clone": "^3.0.3",
"lodash.isequal": "^3.0.4",
"rx": "^4.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment