Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created May 16, 2014 21:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/b57cf50a34f22ba39e4f to your computer and use it in GitHub Desktop.
Save mattpodwysocki/b57cf50a34f22ba39e4f to your computer and use it in GitHub Desktop.
Reactive Extensions with Promises Interactions
// Using concat with promises.
var sources = Rx.Observable.concat(
$.get('foo.json').promise,
$.get('bar.json').promise,
Rx.Observable.return(42) // Hey why not an observable as well
);
sources.subscribe(
function (data) {
// Do something with each piece of data.
});
// Using defer
var source = Rx.Observable.defer(function () {
return $.get('foo.json').promise;
});
// Using zip
var source = Rx.Observable.zip(
$.get('foo.json').promise,
$.get('bar.json').promise,
function (foo, bar) { /* Do something to combine them */ });
// Run in parallel
var source = Rx.Observable.forkJoin(
$.get('foo.json').promise,
$.get('bar.json').promise
);
// What you can't get from promises spec
// Cancellation
var source = Rx.Observable.fromPromise($.get('foo.json').promise);
var subscription = source.subscribe(...);
// Cancel the value of the promise if it hasn't come back yet
subscription.dispose();
// Easy retry
var source = Rx.Observable.fromPromise($.get('foo.json').promise)
.retry(3);
// Either timeout or another value
var source = Rx.Observable.fromPromise($.get('foo.json').promise)
.timeout(500, Rx.Observable.return(42));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment