Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created July 8, 2014 21:11
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/e99bcf4ae092fae569d3 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/e99bcf4ae092fae569d3 to your computer and use it in GitHub Desktop.
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
if (!hasCurrent) {
hasCurrent = true;
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(onError),
function () {
g.remove(innerSubscription);
if (isStopped && !hasCurrent && g.length === 1) {
observer.onCompleted();
}
));
},
observer.onError.bind(observer),
function () {
hasCurrent = false;
isStopped = true;
if (g.length === 1) {
observer.onCompleted();
}
}));
}
return g;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment