First look at RxJS

Alaa Chakroun
eDonec
Published in
2 min readFeb 21, 2021

JavaScript event management made easy

Photo by Ferenc Almasi on Unsplash

Oftentimes, managing events in JavaScript can easily drift out of hand. Fortunately, the community developed many solutions to tackle this very problem, and in this article, we’re going to get a first look at one of these libraries: RxJS.

What is RxJS

As the documentation describes it :

RxJS is a library for composing asynchronous and event-based programs by using observable sequences. It provides one core type, the Observable, satellite types (Observer, Schedulers, Subjects) and operators inspired by Array#extras (map, filter, reduce, every, etc) to allow handling asynchronous events as collections.

Usage

First, let’s take a look at event listening using RxJS by creating a blank React project and a page containing a button. Listening to button click events is as simple as shown in the code below.

If we wanted to keep track of the number of presses, we can easily add the following changes to our Observable.

The scan function acts just like the regular JavaScript Array.reduce method, it emits the current accumulation whenever the source emits a value, in our case the document “click” event.

In this article, we’re going to take a look at 2 simple usage examples that often require developers to write their own implementation and thus, making it more prone to bugs : Throttle and Debounce

Throttle

Instead of writing our own implementation and comparing, keeping track of timestamps and setting up our conditions, RxJS offers us the throttleTime method out of the box, which enables us to achieve the desired outcome in one single line of code.

Debounce

Debouncing is handled exactly the same way as throttling, RxJS provides us with the debounceTime method, so we don’t have to depend on lodash’s implementation (or others).

The snippet down below shows us how easy it is to implement it:

Conclusion

This article has been an early first look at RxJS. On its own, RxJS is a very powerful tool, but where it shines is when it’s combined with the Redux state management library using redux-observable which we are going to explore in a later article.

This has been developed by myself at eDonec

--

--