Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattpodwysocki/c0ae204047cf6086ad1b to your computer and use it in GitHub Desktop.
Save mattpodwysocki/c0ae204047cf6086ad1b to your computer and use it in GitHub Desktop.
function RxBus() {
function identity() { }
function remove(xs, x) {
xs.splice(xs.indexOf(x), 1);
}
function innerSubscription(observable) {
var disposable;
function cancel() { remove(subscriptions, subscription); }
function push(message) { rxBus.push(message); }
function start() {
disposable = observable.subscribe(push, cancel);
}
function stop() {
disposable && disposable.dispose();
}
var subscription = {
start : start, stop : stop
};
subscriptions.push(subscription);
observers.length > 0 && start();
return subscription;
}
var subscriptions = [];
var observers = [];
var rxBus = Rx.Observable.create(function(observer) {
observers.push(observer)
if (observers.length == 1) {
subscriptions.forEach(function(subscription) { subscription.start(); })
}
return function() {
remove(observers, observer);
if (observers.length === 0) {
subscriptions.forEach(function(subscription) { subscription.stop(); })
}
}
});
rxBus.ofType = function(messageType) {
return rxBus.filter(function(message) { return message.message == messageType; });
};
rxBus.push = function (message) {
observers.map(identity).forEach(function(observer) {
observer.onNext(message)
});
return rxBus;
};
rxBus.plug = function (observable) {
innerSubscription(observable);
return rxBus;
};
return rxBus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment