Over the years, we have dealt with the various codes of different projects. We have noticed that RxJS is clearly on the rise, which is certainly due to the fact that Google uses RxJS as part of its Angular ecosystem. But in the vast majority of cases we have seen that the imperative pattern a so-called anti pattern of RxJS is used all the time.
In this post we explain the difference between the imperative and reactive pattern and show the benefits of the reactive pattern using an example in an Angular environment.
RxJs imperative programming
It is a commonly made mistake to subscribe to an observable directly and store the result in an external variable. This contradicts the whole concept of manipulating and transforming data to get different results.
The following example is not wrong in terms of functionality however it does not follow the idea of reactive programming but nests the logic in an observable instead of streaming the data.
Let’s look at a common example of how not to do it.
Apart from the fact that this can cause page effects on your data, you still need to unsubscribe all your listeners once Angular has destroyed the component.
You should avoid subscribing to your Observable in the TypeScript file unless you need to use the result to compute something else. Even though you can use operators like tap to insert the result into an external variable without subscribing to it there.
RxJS reactive programming
Now let’s look at a better way to organize your observables using reactive programming. This type of programming outputs exactly the data you are looking for. So you don’t have to subscribe to variables inside your typescript file, create external variables, or even put up with side effects to get your data. Here in this example we define a stream and transform the content via a pipe.
The main advantage of this implementation is the use of the async pipe, Angular takes care of everything, the component subscribes and unsubscribes automatically. So we don’t have to worry about memory leaks at this point. Also, we use the same observables to filter the result and create a new observable, this makes the code very clear and the individual observables more reusable.
Summary
This simple example illustrates the difference between imperative and reactive programming with RxJS. The advantage becomes clearer in practice when, for example, you work with several observables and they build on each other. A simple reuse of these observables is given with this type of implementation.