Adapt jQuery.getJSON to an Rx.Observable with RxJs

Rx provides an incredible and fluent API to help untangle your asynchronous JavaScript code.
Here we’ll see how to adapt jQuery’s getJSON method to an Rx Observable with only a small bit of code.

function getJSON(url, data) {
  return Rx.Observable.create(observer => {
    var canceled = false;
    if (!canceled) {
      jQuery.getJSON(url, data).
        done(data => {
          observer.onNext(data);
          observer.onCompleted();
        }).
        fail(err => observer.onError(err));
    }
    return () => canceled = true;
  });
}

Now that $.getJSON has been adapted to an Observable, we can full take advantage of all the goodness that Rx provides. For example, let’s ask Rx to automatically retry the request if it fails!

getJSON('https://api.ipify.org', { format: 'json' }).
  retry(3). // retry 3 times, prior to throwing
  forEach(e => console.log(e));

I’ve also posted these snippets as a Gist.

You may also like...

Leave a Reply