2 minute introduction to Rx

You've probably seen this tutorial I wrote some time ago. Too long? Alright. Rx is not that hard, you could have invented it yourself. Keep reading.

You know arrays? Of course you do. Here is one:

[ 14, 9, 5, 2, 10, 13, 4 ]

If I would tell you this is an immutable array and you need to take away all the odd numbers, how would you do it? This is a popular way:

[ 14, 9, 5, 2, 10, 13, 4 ]
filter( (x) -> x % 2 == 0 )
[ 14, 2, 10, 4 ]

Nothing new until now. That's commonplace in underscore.js, ECMAScript 5.1, LINQ, Guava, etc. It comes from the functional paradigm.


Now think about click events with cursor position data. If you draw them on a timeline, they would look like this.

That, my friend, is a stream of events, kindly nicknamed "Observable".

The click events are coming from the mouse, so the stream of events as whole is immutable, in the sense that you cannot add or remove from it after it was defined.

But what if I'm only interested in click events where x < 250? Well can't we just create a new stream by filtering like we did with arrays?

filter( (event) -> event.x < 250 )

So what's the difference between immutable arrays and Observables? Not that much. You can apply map, filter, reduce to both. On Observables, you can also apply merge, delay, concat, buffer, distinct, first, last, zip, startWith, window, takeUntil, skip, scan, sample, amb, join, flatMap.

Think of it as an asynchronous immutable array.

Rx is the underscore.js for events. But wait a second, what is an event? Can't most things in your application be an event?

Event "application started", event "API response arrived", event "keyboard key pressed", event "invalidateLayout()", event "device slept", etc.

Virtually anything can be a stream of events. It's just a matter of composing and combining them properly.

And that's Rx in 2 minutes.

What's the difference between an array and events?
Erik Meijer