Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created January 28, 2013 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattpodwysocki/4657297 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/4657297 to your computer and use it in GitHub Desktop.
Changes to CombineLatest to have a non-prototype based implementation
observableProto.combineLatest = function () {
var args = slice.call(arguments);
args.unshift(this);
combineLatest.apply(this, args);
};
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(function (x) { return x; }))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(function (x) { return x; })) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
@cwharris
Copy link

Sweet! I added a bit, but I don't know if you'll want to include it: https://gist.github.com/4658319

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment