Fork me on GitHub

Clean Composable Code

The Need to go Reactive

Reactive Programming is a hot topic as of late, especially with such things as the Reactive Manifesto. Applications, especially on the web have changed over the years from being a simple static page, to DHTML with animations, to the Ajax revolution. Each time, we're adding more complexity, more data, and asynchronous behavior to our applications. How do we manage it all? How do we scale it? By moving towards "Reactive Architectures" which are event-driven, resilient and responsive. With the Reactive Extensions, you have all the tools you need to help build these systems.

About the Reactive Extensions

The Reactive Extensions for JavaScript (RxJS) is a set of libraries for composing asynchronous and event-based programs using observable sequences and fluent query operators modeled after Language Integrated Queries (LINQ). Using RxJS, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, RxJS = Observables + LINQ + Schedulers. Whether you are authoring a web-based application in JavaScript or a server-side application in Node.js, you have to deal with asynchronous and event-based programming as a matter of course. Although some patterns are emerging such as the Promise pattern, handling exceptions, cancellation, and synchronization is difficult and error-prone.

Using RxJS, you can represent multiple asynchronous data streams (that come from diverse sources, e.g., stock quote, tweets, computer events, web service requests, etc.), and subscribe to the event stream using the Observer object. The Observable notifies the subscribed Observer instance whenever an event occurs.

Because observable sequences are data streams, you can query them using standard LINQ query operators implemented by the Observable type. Thus you can filter, project, aggregate, compose and perform time-based operations on multiple events easily by using these static LINQ operators. In addition, there are a number of other reactive stream specific operators that allow powerful queries to be written. Cancellation, exceptions, and synchronization are also handled gracefully by using the methods on the Observable object.

This set of libraries include:

Why RxJS?

One question you may ask yourself, is why RxJS? What about Promises? Promises are good for solving asynchronous operations such as querying a service with an XMLHttpRequest, where the expected behavior is one value and then completion. The Reactive Extensions for JavaScript unifies both the world of Promises, callbacks as well as evented data such as DOM Input, Web Workers, Web Sockets. Once we have unified these concepts, this enables rich composition.

To give you an idea about rich composition, we can create an autocompletion service which takes the user input from a text input and then query a service, making sure not to flood the service with calls for every key stroke, but instead allow to go at a more natural pace.

First, we'll reference the JavaScript files, including jQuery, although RxJS has no dependencies on jQuery...

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="rx.js"></script>
<script src="rx.async.js"></script>
<script src="rx.binding.js"></script>
<script src="rx.time.js"></script>

Next, we'll get the user input from an input, listening to the keyup event by using the Rx.Observable.fromEvent method.

var $input = $('#input'),
    $results = $('#results');

/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent(input, 'keyup')
    .map(function (e) {
        return e.target.value;
    })
    .filter(function (text) {
        return text.length > 2;
    });

/* Now throttle/debounce the input for 500ms */
var throttled = keyups
    .throttle(500 /* ms */);

/* Now get only distinct values, so we eliminate the arrows and other control characters */
var distinct = keyups
    .distinctUntilChanged();

Now, let's query Wikipedia! We'll use the new Promise bindings which will bind to any Promises A+ implementation through the Rx.Observable.fromPromise method.

function searchWikipedia (term) {
    var promise = $.ajax({
        url: 'http://en.wikipedia.org/w/api.php',
        dataType: 'jsonp',
        data: {
            action: 'opensearch',
            format: 'json',
            search: encodeURI(term)
        }
    }).promise();
    return Rx.Observable.fromPromise(promise);
}

Once that is created, now we can tie together the distinct throttled input and then query the service. In this case, we'll call flatMapLatest to get the value and ensure that we're not introducing any out of order sequence calls.

var suggestions = distinct
    .flatMapLatest(function (text) {
        return searchWikipedia(text);
    });

Finally, we call the subscribe method on our observable sequence to start pulling data.

suggestions.subscribe( function (data) {
    var res = data[1];

    /* Do something with the data like binding */
    $results.empty();

    $.each(res, function (_, value) {
        $('<li>' + value + '</li>').appendTo($results);
    });    
}, function (e) {
    /* handle any errors */
    $results.empty();

    $('<li>Error: ' + error + '</li>').appendTo($results);    
});

And there you have it!

Dive In!

You can find the documentation here as well as examples here and plenty of unit tests.

Resources

Getting Started

There are a number of ways to get started with RxJS. The files are available on cdnjs and jsDelivr.

Download the Source

git clone https://github.com/Reactive-Extensions/rxjs.git
cd ./rxjs

Installing with NPM

npm install rx
npm install -g rx

Using with Node.js and Ringo.js

var Rx = require('rx');

Installing with Bower

bower install rxjs

Installing with Jam

jam install rx

Installing All of RxJS via NuGet

Install-Package RxJS-All

Install individual packages via NuGet:

Install-Package RxJS-Main
Install-Package RxJS-Aggregates
Install-Package RxJS-Async
Install-Package RxJS-Binding
Install-Package RxJS-Coincidence
Install-Package RxJS-Experimental
Install-Package RxJS-JoinPatterns
Install-Package RxJS-Testing
Install-Package RxJS-Time

In a Browser:

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

Along with a number of our extras for RxJS:

<script src="rx.aggregates.js"></script>
<script src="rx.async.js"></script>
<script src="rx.binding.js"></script>
<script src="rx.coincidencejs"></script>
<script src="rx.experimental.js"></script>
<script src="rx.joinpatterns.js"></script>
<script src="rx.time.js"></script>
<script src="rx.virtualtime.js"></script>
<script src="rx.testing.js"></script>

Using RxJS with an AMD loader such as Require.js

require({
    'paths': {
        'rx': 'path/to/rx.js'
    }
},
['rx'], function(Rx) {
    var obs = Rx.Observable.return(42);
    obs.subscribe(function (x) { console.log(x); });
});

What about my libraries?

The Reactive Extensions for JavaScript have no external dependencies any library, so they'll work well with just about any library. We provide bridges and support for various libraries including:

In addition, we have support for common Node.js functions such as binding to callbacks and the EventEmitter class.

Compatibility

RxJS has been thoroughly tested against all major browsers and supports IE6+, Chrome 4+, FireFox 1+, and Node.js v0.4+.

Contributing

There are lots of ways to contribute to the project, and we appreciate our contributors.

You can contribute by reviewing and sending feedback on code checkins, suggesting and trying out new features as they are implemented, submit bugs and help us verify fixes as they are checked in, as well as submit code fixes or code contributions of your own. Note that all code submissions will be rigorously reviewed and tested by the Rx Team, and only those that meet an extremely high bar for both quality and design/roadmap appropriateness will be merged into the source.

License

Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Microsoft Open Technologies would like to thank its contributors, a list of whom are at http://rx.codeplex.com/wikipage?title=Contributors.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.