RxJS — Why should you learn it?
Hey everyone,
If you work with the Angular framework it is highly possible that you’ll come across with the RxJS library. So, what is RxJS and why it is important to learn it?
RxJS is a reactive library for Javascript. In summary, it is a library for filtering, sorting and coordinating data.
When working with the JavaScript language we often have to handle asynchronous operations. APIs calls and events are examples of async operations. Whenever these operations emit data, we have to send this data to a component which will be responsible for handling it. However, let me ask you an important question.
Should components be responsible for handling raw data from asynchronous operations?
The answer is: No, components shouldn’t be worried about handling raw data.
The answer above doesn’t mean that components will never have to handle data. Still, is always a good practice to process data before sending it to a component.
Another scenario that may generate some difficulties is the need to share data between components that doesn’t share a parent-child relationship. That is why RxJS is so useful. It works as a middle man solution between the response from an asynchronous operation and a component.
Alright, now that we have an overview of what RxJS is and what it helps you with, let’s talk about the most fundamental concept of this library which is: Observables!
OK. But, what is an Observable?
You can think of an observable as a wrapper around the data source.
The data can come from numerous sources such as asynchronous operations, mouse events, keyboard events and file uploads. When data is emitted from these sources we can capture the data and give it some treatment before sending it off to whoever need it. An Observable gives us the opportunity to sort, filter and coordinate the data. It addresses the problem we discussed in the beginning of this article. By wrapping the data source we can further refine the data.
An Observable has its name because it can “observe” a data emitted from a source. What a descriptive name, right? hahah
Another important concept in RxJS is called Observers.
While Observables emit data, Observers are responsible for receiving the data emitted from an Observable. The connection between these two guys are called a Subscription.
RxJS allows multiples observers subscribe to a single observable. This is a very powerful feature that permit that different parts of your code receive the same stream of data.
If we format data within an Observable we can guarantee that every Observer that subscribe to this Observable will receive the same formatted data.
Observers never have to worry about how the data was formatted. This relationship allows us to separate responsibilities within our code.
I hope this simple article gives you an idea of what RxJS is and why it is a good tool for us to use in our projects.
Nice coding!!