Subscriptions
Several ways to unsubscribe Observables in vanilla JS and Angular

v.7

v.18

Fabio Biondi
Google Developer Expert
Microsoft MVP
# Introduction
In RxJS, a subscription represents the execution of an Observable.
When you subscribe to an Observable you are essentially starting the flow of data or events from that Observable.
The subscription ties the Observer (which defines how to handle emitted values, errors, and completion) to the Observable.
# It's a contract
You can think of a subscription in RxJS as a kind of "contract" between the Observable and the Observer.
This contract can be stored in a constant, i.e. sub
:
The type of sub
is inferred as Subscription
.
# Unsubscribe
The Subscription
object provided several methods but one of the most used is unsubscribe
that is called when we want to stop receiving notifications and clean up resources.
In the following example:
- we subscribe the
interval
observable. The console prints 0
, 1
, 2
and so on.
- the
Subscription
contract is saved in the sub
constant.
- when we
click
any part of the screen the Observable is unsubscribed because of sub.unsubscribe()
.
Run the snippet below and see how the console.log
displays values until you click the viewport:
# Why should we unsubscribe?
Unsubscribing from an Observable is crucial because it prevents memory leaks and unintended behavior in your application.
When you subscribe to an Observable, it keeps running and consuming resources, even if the component or service that created the subscription is no longer in use.
If you don’t unsubscribe, the Observable may continue emitting values, leading to performance issues as the number of active subscriptions grows, especially in long-lived applications.
Additionally, failing to unsubscribe can cause side effects like multiple subscriptions triggering unintended duplicate actions.
# Angular & Unsubscribe
In this Angular example:
- the
interval()
Observable is subscribed and we save the subscription in the sub
class property.
- the emitted values are stored in the
count
signal and displayed in the template.
- we can unsubscribe at any time just clicking the "Unsubscribe" button
# Unsubscribe on Component Destroy
A very common scenario is to unsubscribe when an Angular component is destroyed, for example at root change.
This is just an example that we have created to show you the syntax.
Of course app-root
component will never be destroyed (since it's just the root component), so ngOnDestroy
lifecycle method will never be invoked in this snippet.
# takeUntilDestroyed
operator
# Use the async
pipe!
Unblock the content
It's completely free!