Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active December 31, 2015 04:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/7937048 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/7937048 to your computer and use it in GitHub Desktop.
Pause/resume semantics on an Observable.
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
var self = this;
return observableCreate(function (observer) {
var conn = self.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
});
};
var pauser = new Rx.Subject();
var source = Rx.Observable.interval(1000).pausable(pauser);
var subscription = source.subscribe(
function (x) {
console.log('onNext: ' + x);
},
function (err) {
console.log('onError: ' + err);
},
function () {
console.log('onCompleted');
}
);
var isRunning = true;
setInterval(function () {
pauser.onNext(isRunning);
isRunning = !isRunning;
}, 5000);
// => next: 0
// => next: 1
// => next: 2
// => next: 3
// => next: 0
// => next: 1
// => next: 2
// => next: 3
// => next: 0
// => next: 1
// => next: 2
// => next: 3
@cwharris
Copy link

So basically this is great for a lossy implementation. Something along the lines of sample. But what if we didn't want to resubscribe? What if we wanted the underlying observable/producer to actually pause?

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