Logo

dev-resources.site

for different kinds of informations.

Unsubscribe Observable! why is it so important?

Published at
12/23/2024
Categories
angular
rxjs
frontend
Author
asaf_eliasim
Categories
3 categories in total
angular
open
rxjs
open
frontend
open
Author
12 person written this
asaf_eliasim
open
Unsubscribe Observable! why is it so important?

In Angular, Observables are commonly used for asynchronous operations, like HTTP requests, user input events, or WebSocket messages. While Observables are powerful and efficient, one common pitfall developers can encounter is not unsubscribing from them when they are no longer needed. This can lead to memory leaks β€” where the application continues to hold onto resources (memory) that should have been released.

Let's explain the issue with a real-life metaphor

The Water Tap and the Bathtub

water-tap-image
Imagine your application is like a bathtub, and Observables are like water taps filling the bathtub. When you create an Observable, it’s like turning on the tap. The data from the Observable keeps flowing into your app, just like water fills the bathtub. If you don’t close the tap (unsubscribe), the water keeps flowing endlessly, and the bathtub fills up indefinitely. Over time, this will cause issues, like an overflowing bathtub, just like a memory leak happens in your application when you don't unsubscribe from Observables.
If you keep the tap running (don’t unsubscribe), your resources (memory) will eventually run out. The water (data) might even spill over and cause problems in other parts of the house (application). It’s a slow and often hidden process, but if unchecked, it will degrade your app's performance over time.

How It Causes Memory Leaks

When you subscribe to an Observable and don’t unsubscribe, your application listens to the stream even after the component or service that initiated the Observable is no longer in use. This means that Angular will still hold onto the subscription object in memory, keeping it alive. If this happens multiple times, it can result in accumulated memory usage β€” which is what we call a memory leak.
For instance, when a component is destroyed, if you don't unsubscribe, the Observable may continue emitting values to a destroyed component that no longer exists in the DOM. This can accumulate over time and cause the browser to consume more and more memory, slowing down or even crashing the application.

Different ways to unsubscribe observables and prevent a memory leak issue ❕❕

βœ… Unsubscribe in ngOnDestroy
To ensure the observables are cleaned when the component is off, unsubscribe all observables inside the life hook.

unsubscribe

βœ… Using 'rxjs' operator 'takeUntil'
It is a wonderful way to automatically clean subscriptions, especially when there is more than one observable.
The operator automatically unsubscribes from observables when a specified condition is met.
Take the emitted values until you met the condition.
Usually, we will use a _destory$ Subject and emit a null value inside the life hook on destroy as our action to kill all subscribers.

take-until

βœ… Async pipe
The pipe subscribes to an Observable and returns the latest value it has emitted. When a new value is emitted, it marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically. It reduces manual subscription management in the model.

Aync pipe

βœ… DestroyRef
Those developing using Angular >= 16 can use this awesome provider (which provides you) to run a callback (unsubscribe) when the component is destroyed. 🀩

DestroyRef

To summarize 🀯
Angular's developers or any other developers that are using the wonderful observables of 'RXJS' keep your subscriptions alive as you never keep your water tap, and every time you fill a bathtub, think about your last feature if you used observables and ensure to unsubscribe them.

rxjs Article's
30 articles in total
Favicon
rxjs
Favicon
Angular Signals and Their Benefits
Favicon
Migrando subscribe Callbacks para subscribe arguments no RxJS
Favicon
New in Angular: Bridging RxJS and Signals with toSignal!
Favicon
RxSignals: The Most Powerful Synergy in the History of Angular πŸš€
Favicon
Virtually Infinite Scrolling with Angular
Favicon
Building a Collapsible UI Component in Angular: From Concept to Implementation πŸš€
Favicon
Disabling button on api calls in Angular
Favicon
Angular Dependency Injection β€” Inject service inside custom Rxjs operators
Favicon
Unsubscribe Observable! why is it so important?
Favicon
Harnessing the Power of RxJS with React for Asynchronous Operations
Favicon
DOM Observables, Rx7, Rx8 and the observable that doesn't exist yet
Favicon
Advanced RxJs Operators You Know But Not Well Enough pt 2.
Favicon
Observables in Node.js: Transforming Asynchronous Chaos into Elegant Code
Favicon
Reusable, Extensible and Testable State Logic with Reactive Programming.
Favicon
Understanding RxJS and Observables in Angular: A Beginner-Friendly Guide
Favicon
Are Angular Resolvers on Life Support ?
Favicon
Creating Custom rxResource API With Observables
Favicon
Forestry: The Best State System for React and (not React)
Favicon
πŸ“’ Announcing the New Reactive State Management Libraries! πŸŽ‰
Favicon
Reactables: Reactive State Management for any UI Framework.
Favicon
Hot vs Cold Observables in Angular: Understanding the Difference
Favicon
RxJS Simplified with Reactables
Favicon
How I structure my Angular components with Signals
Favicon
Angular LAB: let's create a Visibility Directive
Favicon
Difference between mergeMap vs switchMap vs concatMap vs exhaustMap
Favicon
How Signals Improve Your App Performance
Favicon
The Article I Took So Long to Write: Concepts about Reactive Programming and RxJS
Favicon
Tame Your Asynchronous World with RxJS
Favicon
Custom RxJS Operators to Improve your Angular Apps

Featured ones: