Intro to RxJS

RxJS is the JavaScript version of a .net library that amongst other things makes it easy to handle, combine and filter events.

I gave a talk about RxJS last week – my slides and code examples are available here.

On a recent project a colleague (Hendry Luk) suggested we utilize RxJS to solve a tricky issue we were having. We were developing a web based calculator to be used by financial consultants. The calculator contained a number of fields the consultants could modify to then see the effect they would have on their clients income. The client wanted the output to be automatically updated when any changes were made. Our initial implementation felt a bit clunky as we bound to every key press, select box change etc. Thus when a user was typing into a textbox a request was made on each key press and the output rebound.

There is obviously a few ways to solve this but RxJS made it very easy. RxJS allowed us to throttle this process and ignore out of date values e.g. if a value was changed before a pending response had returned.

For me I think getting started with Rx is probably the hardest part as there are currently few very basic examples around and it can be a bit confusing whats actually going on.

Let’s create a simple hello world example to demonstrate some of the main concepts.

We will create a simple web page containing a single button that does the following:

  • When the button is clicked we will ignore the first 2 clicks
  • We will display an alert for clicks 3 and 4
  • After clicks 3 and 4 an alert box saying “done” will appear

Let’s get started, first create a new html page called helloRx.htm.

RxJS has many different libraries (see above section) that offer rich functionality such as extensions for working with jQuery, testing & combining events but for our example we just want the core library (rx.js) so let’s import this:

<script src="rx.js"></script>

Now we want something that will trigger an event (an observable in RX terminology) so add a button to the page:

<button id="button">Click me!</button>

Now we need to turn the buttons click event into something RX can work with so we will create a function that wraps the Rx.Observable.create method (note the rx.jquery.js library allows you to do this in one line with methods such as clickAsObservable):

function CreateObservable(element, eventType) {
return Rx.Observable.create(function(observer) {
function eventHandler (eventObj) {
observer.onNext(eventObj);
}
//keep simple for this example and ignore addEventListener/attachEvent browser differences
element.addEventListener(eventType, eventHandler);
return function() {
element.removeEventListener(eventType, eventHandler);
};
});>
};

Now we will use this function to create an observable from our buttons click event. We will also use the methods skip and take on our observable to skip the first 2 clicks and tell rx we are only interested in the next 2 clicks.

var observable= CreateObservable(document.getElementById('button'), 'click')
.skip(2)
.take(2)
.select(function(evt){
return "button was clicked"
});

Next we need to create an observer to monitor our observable:

var observer = Rx.Observer.create(
//onNext
function(evt) {
alert(evt);
},
<p>//onError
function(err) {
alert('error');
},
<p>//onComplete
function() {
alert('done');
}
);

Note how you can (optionally) pass 3 functions into Rx.Observer.create method. The first (onNext) handles an event occurring, the second errors and the third completion of an observable sequence.

Finally we need to link (or subscribe) the observer to our observable with a call to the observables subscribe method:

observable.subscribe(observer);

Now run this in the browser and congratulate yourself for getting started with RxJS!

Whilst this wouldn’t be too hard to accomplish with traditional methods you can start to get an idea of the power and readability offered by Rx.

Advertisements