2 minute introduction to Rx

André Staltz
Jul 30, 2014 · 2 min read

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

André Staltz

Written by

Reactive programming expert, JavaScript functional programmer at @futurice, http://reactivex.io addict, http://cycle.js.org creator. http://staltz.com

André Staltz

Written by

Reactive programming expert, JavaScript functional programmer at @futurice, http://reactivex.io addict, http://cycle.js.org creator. http://staltz.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store