RxJS Functions (Part 1)


Reactive programming is cool.

It’s becoming more and more clear that the future is web, and the future of the web is reactive. That means now is the time to learn these concepts.

In an effort to better understand reactive programming (specifically ReactiveX/RxJS), I’ve decided to learn by doing. In this multi-part series, I’ll create one example per day¹ illustrating the use of a function² from the RxJS API.

Each example will be the simplest one I can come up with to illustrate the purpose of the function. This is not a deep dive on the inner workings of the library, so explanations will only be as verbose as needed to explain the code. If you’re not familiar with ReactiveX at all I’d suggest reading up on it first. I’m assuming some experience with the use of Observable.


Give it a function f of type f(x, callback) and it will return a function g that when called as g(x) will output an Observable.

Out of the gate, the first function in the API list can be a little confusing if you haven’t seen something like it before. bindCallback is one of several functions used to create a new Observable. If you’re familiar with JavaScript a ‘callback’ should feel pretty normal, and we’re going to create an Observable from a function that takes a callback.

Here’s a web example of a common callback usage:

Every time the document receives a click event, the onClick function will be called, and we log out the x, y coordinates of the click.

We can convert this function that takes a callback into a function that returns anObservable using bindCallback:

Voila! Now when we click on the document, our Observable emits the click event, and our onClick handler will output 123 456 (YMMV).

But wait, you may have noticed that the event only seems to fire once. If you click multiple times only the first event gets logged to the console. This is because the Observable that bindCallback creates completes after the first event is emitted. Thankfully, RxJS provides a fromEvent function which will create an Observable that emits for every event instead of just one.

In a contrived example like this, bindCallback can seem to have limited usefulness. But if you find yourself with an older codebase littered with async callback functions, and you’re in the process of refactoring to become more ‘reactive’, it could be a life saver.

Thanks for reading, and stay tuned for Part 2.

¹ My goal is 1 per day, but we’ll see.

² As of this writing, the RxJS docs allow filtering by ‘function’, and automatically sort alphabetically. I’ll be starting a the top of this list and working my way down.

ReactiveX and the ReactiveX logo belong to http://reactivex.io/.