Skip to content

Instantly share code, notes, and snippets.

@kaplas
Last active December 16, 2015 22:29
Show Gist options
  • Select an option

  • Save kaplas/5507695 to your computer and use it in GitHub Desktop.

Select an option

Save kaplas/5507695 to your computer and use it in GitHub Desktop.
Helper method for combining latest values from different RxJS observable streams into a new stream based on a JS object template.
// construct function copied from
// http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible/#1608546
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
function combinedMappedStreamBasedOn(template) {
var keys = _.keys(template);
var streams = _.values(template);
var generator = function () {
var args = Array.prototype.slice.call(arguments);
var json = {};
_.each(args, function (arg, index) {
json[ keys[index] ] = arg;
});
return json;
};
var argumentsForCombineLatest = streams.concat([generator]);
var combinedStream = construct(Rx.Observable.combineLatest, argumentsForCombineLatest);
var replaySubject1 = new Rx.ReplaySubject(1);
combinedStream.subscribe( replaySubject1 );
return replaySubject1;
}
// Usage example
// -------------
var combinedStream = combinedMappedStreamBasedOn({
traveller: travellerS,
country: selectedCountryS
});
combinedStream.subscribe(logWith('expense claim'));
// logs the expense claim as a JS object:
// {
// traveller: /* latest value from the travellerS stream */ ,
// country: /* latest value from the selectedCountryS stream */
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment