Skip to content

Instantly share code, notes, and snippets.

@storkme
Last active August 29, 2015 14:08
Show Gist options
  • Save storkme/4c721452ab3ad0bd11de to your computer and use it in GitHub Desktop.
Save storkme/4c721452ab3ad0bd11de to your computer and use it in GitHub Desktop.
Playing about with RxJs
var Rx = require('rx');
function doSomeAsyncThing(code) {
return Rx.Observable.return({
a: "product a",
b: "product b",
c: "product c",
d: "product d"
}[code]).delay(500 + (Math.random() * 5000));
}
var products = Rx.Observable.fromArray([
{
id: '1545',
name: 'product',
codes: ['a', 'b']
},
{
id: '2984',
name: 'product 2',
codes: ['c', 'a']
},
{
id: '3059',
name: 'product 3',
codes: ['c', 'a', 'd']
}
]);
// Grabs the codes of all items
products
.flatMap(function (product) {
var newProduct = Object.create(product);
console.dir(newProduct);
newProduct.productInfo = {};
return Rx.Observable.fromArray(newProduct.codes)
.flatMap(function (code) {
return doSomeAsyncThing(code).map(function (desc) {
return {code: code, description: desc}
});
})
.reduce(function (acc, elem) {
acc.productInfo[elem.code] = elem.description;
return acc;
}, newProduct);
})
// Display the aggregated value
.subscribe(function (product) {
/**
* note: since these products prototypically inherit from our original product,
* console.dir won't show all of the inherited stuff in our products, just the new jazz.
*/
console.dir(product);
});
// what a wonderful time to be alive.
// special thanks to @robotlolita for the patience!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment