RxJS: the art of responsive programming with Angular

Vincenzo Saccotelli - 2023-03-17

Discover the art of responsive programming with Angular and RxJS. Handle asynchronous events and optimize your code. Learn how to use Observable, Observer, Subscription, and RxJS operators to create data streams and manipulate them.

RxJS is an event-driven library of Javascript, which can be used with React, with which it is possible to handle sequences of events that may occur in a web application.

RxJS, in particular, is a great tool that allows us to handle asynchronous events very efficiently. Reactive Extensions Library for JavaScript comes to our aid when we need to develop an application with a type of reactive programming.

Having even a basic knowledge of this library can help you to write cleaner code. In many cases also to have an easier management of the same code (with exceptions of course!).

Index



  1. What is reactive programming with RxJs
    1. Observable, Observer and Subscription in reactive programming
    2. Operators for creating observables in RxJS
    3. RxJS: manipulating observables
    4. What are Marble Diagrams
  2. Reactive programming with RxJs in Angular
    1. What are Subjects and their use in Angular 
  3. Conclusions

What is reactive programming with RxJs

Reactive programming is a way of programming in which the application is always ready to respond to any changes that occur within the system.

With reactive programming you write code that is constantly listening for events or changes in the state of the application.

In RxJS, this is possible through the use of Observables. Let's see what they are and how they work.

Observable, Observer and Subscription in reactive programming

In RxJs a data stream is called an Observable, and in order to access this data we need to perform a subscription (Subscription). Whenever we have new data on the stream a function will be executed, all asynchronously.

When we use Observable data types, we need an object that observes the data and is able to receive its values. We are talking about an Observer.

Think for example, a form that receives data entered by the user. When the user fills out the form, the data is sent as a data stream to the Observable, which in turn notifies the Observer of the data entered by the user. For example, via a backend function.



Example of observer

Source: RxJS Dev

We can see that an Observer has multiple callbacks where:



- next: is the function, always present, that is called each time when new data is sent to the stream;

- error: is the method that is used by the Observer when it receives an error. In this case theexecution of the Observable is aborted;

- complete: this function is used to receive a worthless notification;



Good, but now we need to understand how we can create our flows and possibly manipulate them.

Never fear, RxJs puts at our disposal the operators, let's see how to do it.

Operators for creating observables in RxJS 

In RxJS the most common creation operators we find of(), from(), fromEvent(source, 'event').

The operators of() e from() are similar because both are used to create observable data and send it one after the other. The difference is that from() uses data from an Array or Promise, while of() creates it directly.

Instead, with the operator fromEvent(source, 'event') we can create an observable from an event. In the function we must use two arguments as input: first, the source emitting the event and, second, the type of event.

For example, think of a search field where we go to intercept the event keyup() of the keyboard. With fromEvent() we can capture the event, isolate the input value, and eventually leverage it to make an HTTP call to a back-end server.

RxJS: manipulating observables

In addition to Observable creation, with RxJs it is possible to filter, map, concatenate, combine, pass from one stream to another etc. with ease thanks to thepipe operator.



But let's go in order... 



Before doing the Subscription to our Observable it is possible that our data needs to be shown differently from how it comes from the stream; therefore, we need to make some changes.



For example, let's think of a stream of numbers that comes to us in the form of an Observable, however, we are interested in having all those numbers multiplied by ten in the output.



Okay, what do we do?



Sure enough, we first create a stream and, since our numbers are not part of an Array and not derived from a Promise, we use the operator of(). Before we subscribe to theobservable, we concatenate the operator pipe() and inside it we go to use map(), which will take every single piece of data and we tell it to multiply it by ten.



Edit observable data

Similarly, we can use other operators that RxJs also makes available to us in combination with each other. For example, suppose we want to multiply by ten only multiples of two; in this case before map() we will use the operator filter().



Filtering Numbers with RxJS Operators

What are Marble Diagrams

To understand the behavior of an Observable, especially after applying one or more operators, we can make use of a tool, the so-called Marble Diagrams.



Marble Diagrams

Let's take an example found on the official documentation and try to interpret it.



Observable data stream

In the first part, the initial data stream is represented, which consists of numbers, so we have an Observable.



Edit stream in RxJS

In this rectangle, the operator we are using to modify the stream data is usually inserted.



Observable filtered

At the end, the observable with the filtered data is shown.

Reactive programming with RxJs in Angular 

Since the release of Angular 2.0 the RxJs library has been introduced. which provides, precisely, the Observable data type.



One example, probably the most widely used, is related to HTTP calls where through the modules HttpClientModule e HttpClient we have the ability to query a server and have it return data in the form of an Observable, with all the benefits that it entails.

Assuming that we want to retrieve a list of users from a server via an API call, with Angular we are going to use the modules mentioned above that will transform and return the call into an Observable; in this way:



Retrieving a list of users via API call

The method getUsers() is what we are interested in and that is where our data stream will be enclosed, but until we make a subscription, we cannot take advantage of this data. So the second step will be to make a Subscription, collect the data and display it graphically, let's go!



Subscription

In another component, in its .ts (TypeScript), we are going to subscribe to theObservable, and since we are now in the Observer, via the next() method we can take our data (array of users in this case) and copy it into a variable (users) of our component that we are going to use in the .html where the names of the users will be displayed.



Next() method

Eventually, we can use our array of users and display it graphically.



Output array of users

As in the previous examples, we can concatenate the pipe() operator and make changes to our flow before doing the Subscription according to our development needs!

If we had not used the BehaviorSubject in the service, we would have burdened the application both on the back-end side but also on the front-end side since in order to get our list of users we have to call up the server! 

Obviously we are talking about only two components here, but imagine in an application with hundreds of components and services how many server calls we could save. 

Another use of reactive programming in Angular is related to forms, and just for that it provides us with a module, ReactiveFormsModule, with which we can manage our forms in a very efficient way thanks to controls that we will do directly in our .ts file.

What are Subjects and their use in Angular 

I Subject are special types of Observables that are used to perform the multicasting of information, that is, transmitting one piece of information to multiple Observers.



Subject for multicasting information

What we will see in the console resulting from the code written above will be:



Display in console

We note that the value 1 is not shown, this is because Subjects informs the Subscribers of the notified values only after a Subscription by a Subscriber, while value 2 is received only by the first Subscription but not by the second.

The special feature of Subjects is that, by simply invoking the next() method, they allow us to output values. 

There are 4 types of Subject, but we will give an example using one of them, viz. BehaviorSubject, but of course I invite you to learn more about the others.

An integration in an Angular project of BehaviorSubject could be effective for us when we need to display data to multiple components, storing the latter in a service.



Our service will result as follows:



Operator BehaviorSubject

A BehaviorSubject needs an initial value, and since we know that the server will return an array of users we initialize it with empty arrays. 

With thepipe() operator of RxJs, I go to map with map() the response (if any) from the server and pass it with the next() to our BehaviorSubject.



Pipe() operator

Let's now see how to retrieve this data and with a single Subscription done in the AppComponent component in this case, we can then keep the list of users in memory and also display it in another component that we will call ChilComponent.



In the .ts file of AppComponent we initialize a property users$ of type Observable, this is because we are going to use in method asObservable() on our BehaviorSubject which will return a new Observable that we can use in the .html file with Angular's async pipe.



Method asObservable() on the BehaviorSubject

So we will have: 



Result of asObservable() on the BehaviorSubject

In the ChilComponent we will have this situation:



ChilComponent Visualization

We no longer have to make a call to the server here, but can directly take advantage of the data that the BehaviorSubject will keep in memory. In this way we also 'lighten' the back-end by handling a front-end side state. 

So upon clicking on 'Show Daughter List' we will have our list of users without calling up a back-end:



Daughter List



Conclusions 

RxJs is a great tool for developing responsive applications but also for managing states. 

Its use in Angular is very much present and the tools it provides us with are really many and very effective. With this library we can give a boost to our projects, make them more readable code-wise and even, why not, more modern!



I invite you, if this topic fascinates you, to learn more about the use of Subjects and use RxJs operators in your projects, both studio and real-world. Front-End.

Vincenzo Saccotelli

The author of this article has worked at Ulixe since 2022 as a Front-End Developer. He loves a challenge and for him learning never ends. He is a bit of a vintage person, which explains his passion for analog photography, 80s-90s music, and flannel plaid shirts. Travel is a constant in his.

Back on our blog for insights from the world of Front-End development!


See More Posts

background

Be My Eyes: The AI breakthrough for accessibility

Samuel Capano

background

WWDC 2024: New Libraries for iOS Developers

Pierpaolo Pignelli

background

From Ciphers to Computers: Enigma and the Cryptography Revolution.

Alessandra Bertini

Show more

Ulixe Group S.r.l. Copyright © Ulixe Group S.r.l. | Lungo Dora Pietro Colletta, 67, 10153, Turin, Italy | VAT IT03305250122 | Rea Number TO1173020