Automatically Unsubscribe from RXJS Observables in Angular Components

Angular uses RxJS heavily, and often this question comes up: “Should I manually unsubscribe from observables in my components?” Generally, RxJS is pretty good about cleaning up after itself, as it was designed for use in a “fire-and-forget” way most of the time. So, in most cases, it isn’t necessary to unsubscribe manually. However, if you prefer to be diligent, I’ll introduce you to a way to make unsubscribing from observables in your components clean and quick.

Finite and Infinite Observables

First, let’s discuss two broad categories of observables, finite and infinite. Finite observables generally return a single response, such as an HTTP request. When these observables emit their value, they call complete() disposing of the subscription.

Infinite observables have a lifetime longer than the lifetime of the subscription and may continue emitting values after a component is destroyed. Of the two, these pose the greater risk of a memory leak or other complications. So, to be safe, I prefer to ensure all my subscriptions are disposed of in my Angular projects.

Superclass Standalone Component

We’ll start by creating a standalone component responsible for handling closing subscriptions. We will use the Angular CLI to generate our component and include some flags to get our boilerplate code configured to our needs.

ng g c auto-unsubscribe --standalone --inline-template --inline-style --skip-selector

These flags will initialize our component as a standalone component, inline both the HTML template and style, and skip including the selector.

In this component, we will create a protected field destroyed$ of type Subject<void>. Next, we will implement the OnDestroy interface from the @angular/core module. In the ngOnDestroy lifecycle method, we emit an event from our destroyed$ subject and close it. This subject will be used in a takeUntil pipe in subscriptions in the subclass. Those subscriptions will be disposed of when we emit an event from the subject.

Usage

Now, let’s put our new component superclass to use. Because we set it up as a standalone component, we don’t need to declare it in any module, and we are free to use it anywhere in our project.

In our desired component, we can extend our AutoUnsubscribeComponent to gain access to the destroyed$ subject and the OnDestroy functionality we implemented. We can add the takeUntil pipe for any observables we want to unsubscribe from automatically in that component. For example:

Automatically Unsubscribe from RXJS Observables in Angular Components

That simple setup is all it takes to ensure your subscriptions are appropriately disposed of in your Angular components.

Conversation

Join the conversation

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