Unsubscribing from Observables

Learn how to unsubscribe from observables including manual unsubscription and subject-based unsubscription.

When we subscribe to observables, they are prone to potential memory leaks if we do not clean them up on time. In this lesson, we will learn about different ways to accomplish that.

When we subscribe to an observable, we create an observer that listens for changes in a data stream. The observer watches the stream continuously while the subscription remains active. When a subscription is active, it reserves memory in the browser and consumes certain resources. If we do not tell the observer to unsubscribe at some point and clean up any resources, the subscription to the observable will possibly lead to a memory leak.

Note: An observer usually needs to unsubscribe when the Angular component that has created the subscription needs to be destroyed.

Some of the most well-known techniques to use when we are concerned with unsubscribing from observables are the following:

  • Unsubscribe from an observable manually.

  • Use the async pipe in a component template.

Let’s see both techniques in action in the following sections.

Destroying a component

A component has lifecycle events we can use to hook on and perform custom logic. One of them is the ngOnDestroy event, which is called when the component is destroyed and no longer exists.

Recall ProductListComponent and ProductViewComponent, which we studied earlier. They subscribe to the appropriate methods of ProductsService and ProductViewService upon component initialization. When components are destroyed, the reference of the subscriptions stays active, which may lead to unpredictable behavior. We need to manually unsubscribe when components are destroyed to clean up any resources properly:

  1. Open the product-list.component.ts file and add the following import statement:

Get hands-on with 1200+ tech skills courses.