Asynchronous programming and Rx-anything

In this article, we will explore the basics of reactive programming and how we can leverage reactive libraries to enhance our applications.

William Amaral
7 min readSep 24, 2023
Photo by Artem Maltsev on Unsplash

As front-end developers, many times we must deal with some API requests or do anything that requires asynchronous operations. Though the modern frontend frameworks can have a native way of handling it, sometimes we need to harness the power of the reactive paradigm ourselves.

Okay, so, how we can start doing this?

The first thing, that we need to know, is what exactly is the reactive paradigm. And how this can help us in the frontend day-to-day tasks.

Diving into the fundamentals

In a nutshell, the reactive paradigm is nothing more than a way that we can handle the data flow through our applications, as an async way. For example, when you perform an API request, the time that has passed between the started moment and the final, when the HTTP responds with success (200) or error (400 and so on) you can permit the users to do anything they want, and with that, not blocking the UI while he is waiting.

The main idea here is that this paradigm offers a fine-grained way to focus on what was important, the events through the app, and not on how to implement these behaviors, it is more like "what to do" and less "how to do".

This approach has more significant similarities with functional programming, in which the core idea is to use functions to simplify code and enhance readability and maintainability in our codebase. This includes concepts like higher-order functions, immutability, etc. You can find more details about these concepts in this article.

But, truth be told, everyone knows that the learning curve of reactive programming can be challenging. Even when libraries like RxJs provide a less painful way to implement reactive concepts, it can still be difficult to understand and put into practice.

The Reactive Manifesto

If you don't know the Reactive Manifesto, you should give it a chance, basically, this is a document that defines the core principles of reactive programming, it was released in 2014 and has over 30 thousand signatures from programmers around the world.

In the actual scenario of technology, we have a lot of applications that need to run in every place, from mobile devices to cloud-based applications, and our systems need to be resilient and of course, reactive to achieve the specifications usages in a world of constant changes.

Systems built as Reactive Systems are more flexible, loosely-coupled and scalable. This makes them easier to develop and amenable to change. They are significantly more tolerant of failure and when failure does occur they meet it with elegance rather than disaster. Reactive Systems are highly responsive, giving users effective interactive feedback. — The Reactive Manifesto

The Art of Observable Pattern

To keep matters pretty simple and clean, we need to deep dive into some concepts that will make it easier to get the idea of reactive concepts. The first of them is about the Observable Pattern. This pattern is based on the Publish/Subscribe pattern. In a fewer words, we have a mechanism named Event Bus, that is responsible for routing the events to the appropriate subscribers whenever a new event is generated by one of the publishers.

Events are messages, that subscribers can listen to

Imagine that you have an interest in knowing when a new product is available for sale in whatever shop, in that case, we have two entities: User and Store. So, how can you manage whether to go or not to the store and buy your product dream?

The first prospect, is the quite obvious one, each day, you take your way to the store when reach it you ask for your product, and if not available, you go back home and start again the next day. In programming, we call this long pooling strategy, which is basically a request every time for what you want while waiting for your response.

Sometimes this strategy works fine, but if we have a handful of users that want to know if the product is available? We can end up with a big performance problem in the application. Thankfully, we have the observables for that.

In the Observable Pattern, we have an object called Subject that is responsible for notifying all the objects which have some interest in the state and when it changes, these objects are named Observer. As you can see below:

A subscription mechanism lets individual objects subscribe to event notifications.

The Subject class holds a list of observers and some public methods for registering and unregistering observer objects and of course notify all listeners (observer) when a new event is fired.

The power of ReactiveX and its implementations

In the development community, we have an interesting library that implements the observable pattern for many languages, such as RxJava, RxJS, RxKotlin, Rx-anything, etc. See below the official definition from the ReactiveX docs:

It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.

The most intriguing aspect of these libraries is the usage of pipes, which is not more than a function that can transform our data flow into another thing or use N other operators to combine, filter, map, and compose observables, which for me is pretty delightful handle data flow through the application.

example of data flow through the pipe functions

Let's take a look into the RxJs implementation of these concepts:

const { from } = require('rxjs');
const { tap, filter, map } = require('rxjs/operators');

const numbersSource$ = from([1, 2, 3, 4, 5]);

numbersSource$
.pipe(
tap((value) => console.log('value before map: ', value)),
map((value) => value * 2)
)
.subscribe((value) => {
console.log(`result -> ${value} \n`);
})

/**
value before map: 1
result -> 2

value before map: 2
result -> 4

value before map: 3
result -> 6

value before map: 4
result -> 8

value before map: 5
result -> 10
*/

As you can see we started with a new source (numebersSource$), which will create a stream of values that will be emitted one by one, we add some pipe functions to the flow to print the initial data and multiply the current value for 2 and then print the result in the console.

We have to mention that the observable (publisher) only starts to emit new values when someone calls the subscribe function, which is our observer, as we mentioned earlier.

In the rxjs documentation, you will find some examples of a lot of operators ready to use, and you can come across something called Marble Diagram, at first time it gonna seem scary, but don't worry, it is easy to understand, follow along:

Marble diagram from rxjs documentation

The arrows represent the data flow through the time when a source emits a new value, this value can suffer some transformation, in that case, we have a map operator, that multiplies the current value by 10, and after that, continues the process at the end of the stream, which is represented by the final vertical line at the end of arrow.

Final words

We have a lot of usage for the observable pattern and with the aid of libraries like rxjs we can implement reliable and resilient systems, that can bring more clarity to the asynchronous process. This is very helpful in frontend applications when we need, for example, to deal with a search feature and debounce the request to the server, with the object to avoid unnecessary calls.

Anyway, independent of your usage, I hope these concepts can cast light on your understanding of the reactive paradigm and all the stuff that came along with it. I'm very thankful for having you and reading this article, please let me know your thoughts, and feel free to drop your comment below. See you soon :)

You and I after knowing the beauty of reactive concepts

--

--

William Amaral

Software Engineer | Passionate about Technology and Philosophy. Find more in: williamamaral.com