RxJS and Angular: The Art of Unsubscribing Notifications

Future students of the course “JavaScript Developer. Professional” we invite you to participate in an open webinar on the topic “Making an interactive Telegram bot on nodejs”.

In the meantime, we share the traditional translation of a useful article.


If you are using Angular and the RxJS library, here you will learn all the ways you might need to subscribe to object notifications. Observable and unsubscribe from them!

You can work with code dynamically in this online editor… The complete source code for this article is hosted at this GitHub repository

Introduction

We use RxJS in every Angular app we write. RxJS has a significant impact on the data flow in our applications, their performance, and more.

To avoid memory leaks, it is important to unsubscribe from the notifications emitted by Observable objects in time. This article describes most of the available ways in which Angular components can unsubscribe from notifications emitted by Observable objects.

Let’s start by creating a demo service (DummyService) that will help us track installed subscriptions.

Our demo service will have a single method getEmissionswhich takes scope to log events and returns an Observable issuing ${scope} Emission #n every nth second.

No. 1 – “standard” way

The easiest way to subscribe to and unsubscribe from Observable notifications is to subscribe in the method ngOnInit, creating a property of the class that will store our Subscription, and unsubscribing in the method ngOnDestroy… To simplify things a bit, you can initialize the subscription property with the value Subscription.EMPTYto avoid checking it for null when unsubscribing.

To check that everything works, we will remove the component from the DOM after 3 seconds and see that the unsubscribe is in progress:

As the title suggests, this is the easiest way to unsubscribe. He’s good when you have alone subscription. When there are several subscriptions, each of them will need its own class property and call unsubscribe in method ngOnDestroy

# 2 – Subscription.add Method

RxJS subscriptions have a built-in method Subscription.add, with which you can include multiple unsubscribe conditions in a single Subscription instance. First, let’s create a property of the class, initialized as new Subscription()… Then, instead of assigning our subscriptions to class properties, we call the method Subscription.add… Finally, let’s unsubscribe in the method ngOnDestroy

After opening the console, we should see two subscriptions:

In this approach, we take advantage of the built-in powerful capabilities of RxJS to subscribe and unsubscribe to notifications from multiple Observables without using additional class properties.

No. 3 – AsyncPipe

Angular has many great built-in pipe filters. One of them is AsyncPipe… AsyncPipe takes an Observable, automatically subscribes to notifications from it, and unsubscribes from them when the component is destroyed. Unlike the previous example, here we do not set a subscription in our component, and pass the Observable object to the filter AsyncPipe:

In my opinion, this is one of the nicest ways to use Observable objects in Angular. You just need to create the required Observables and Angular will subscribe and unsubscribe for you.

# 4 – takeUntil operator

There are many useful operators in RxJS. One of them is takeUntil… By operator signature takeUntil it is clear that it accepts an Observable object as a parameter notifier and when notifier issues a value, it unsubscribes source Observable… In our case, we need to notify the Observable about the destruction of the component. To do this, we add a property of the class named componentDestroyed$ (or any other name) like Subject<void> and use it as notifier… After that, it remains only to add the “alert” to the method ngOnDestroy. The resulting code looks like this:

In contrast to the previously described “usual” method, in this variant it is not required to introduce additional class properties if there are several subscriptions. We only need to add takeUntil(componentDestroyed$)and RxJS will take care of the rest.

No. 5 – SubSink library

SubSink Is an awesome library created by Ward Bell… With its help, you can correctly unsubscribe from the Observable inside your component.

First, install SubSink by running the command npm i subsink or yarn add subsink… Then we create a property of the class like SubSink.SubSink can be used in two ways: easy way using a setter and way Array/Add.

The easy way is to use a setter method sink.Способ Array/Add has the same syntax as the native method RxJS Subscription.add… Let’s create a subscription in each of these ways. Then our component will look like this:

# 6 – until-destroy library

Note. This library works differently on Pre Ivy Angular. For more information see documentation

until-destroy Is one of the many great libraries created by ngneat… Using a decorator UntilDestroy it determines which properties are subscriptions and automatically cancels those subscriptions when the component is destroyed. Moreover, instead of class properties, we can use its special operator for RxJS called untilDestroyed

To do this, we just need to apply the decorator UntilDestroy to our component and add the operator untilDestroyed in method pipe() object Observable:

In conclusion, until-destroy is a very powerful library that allows you to automatically subscribe to and unsubscribe from notifications from Observables. In addition, until-destroy there are many possibilities that are not covered in this articleso be sure to take a look github repository!

Summary

We’ve introduced many ways to subscribe and unsubscribe to notifications from Observables. Each of these methods has advantages and disadvantages, as well as a distinctive coding style.

But whichever option you choose, the most important thing is act consistently


Learn more about career prospects

Sign up for an open webinar “Making an interactive Telegram bot on nodejs”.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *