The Best Way To Unsubscribe RxJS Observables In The Angular Applications!

Tomas Trajan
Jan 8, 2019 · 13 min read
Image for post
Image for post
An epic journey to RxJS .subscribe()-less Angular applications by 🐻 at Mount Cook (New Zealand)
Image for post
Image for post

A Short Introduction To RxJS Observables

We can think of RxJS Observable as an potentially infinite async Array with all the conveniences we’re used to like filter or map and much more…

Image for post
Image for post
One of the most information-dense diagram ever created! Make sure to take your time to understand and internalize this!

There are many different ways how to handle RxJS subscriptions in Angular applications

What Are We Going To Learn?

1. The .subscribe() aka “The Memory Leak”

Image for post
Image for post

The component will get destroyed but the subscription will live on

2. The .unsubscribe() Method

Image for post
Image for post
Store reference to the original subscription and use imperative unsubscribe inside of ngOnDestory which gets called during the destruction of the component
Image for post
Image for post
Store multiple subscription references in the subscriptions array and unsubscribe all of them during ngOnDestroy
Image for post
Image for post
Collect subscriptions using subscription.add() method instead in array of subscriptions.

3. Let’s Get Declarative With takeUntil

Image for post
Image for post
Note that we are using .pipe() method of the observable to add operators, in our case takeUntil to the observable chain

The takeUntil() solution is great but unfortunately it comes also with a couple of disadvantages

4. The take(1) For Initialization

Image for post
Image for post
We’re triggering initial search for results based on stored query and every additional search will be result of user interaction. (For example there will be a (onchange)=”searchResult($event.target.value)” in the component template)

Follow me on Twitter to get notified about the newest Angular blog posts and interesting frontend stuff!🐤

Sidenote — The <ng-container> element

Image for post
Image for post
Example of using <ng-container> element to unwrap observable stream and story it in a variable

5. The Fabled | async Pipe

The | async pipes automatically unsubscribes all active subscriptions when component is destroyed

Image for post
Image for post
Example of using | async pipe to unwrap stream of todoState to use it in the template
Image for post
Image for post
Using of a “elvis” — ?. operator to prevent “prop of undefined” errors.

6. The Detour — | async Pipe Taken Too Far 😵

The scientists were so focused on whether they could make it work that they forget to ask themselves if they should…

Image for post
Image for post
The toggle() method is triggered by user interaction
Image for post
Image for post
Using subscribe to set new browser title as a reaction to navigation

Psst… there is a way!

Image for post
Image for post
Enter the | async pipe based side effects 😹

7. The Final Destination — NgRx Effects

Image for post
Image for post
Implementation of NgRx effect. This would still needed to be imported in some NgModule with EffectsModule.forFeature([TitleEffects, …])

Side-effects implemented with the help of NgRx Effects are independent from the component life-cycle which prevents memory leaks and host of other problems!


Image for post
Image for post
Try out @angular-extensions/model library! Check out docs & Github

Recapitulation

That’s It For Today!

And never forget, future is bright

Image for post
Image for post
Obviously the bright future! (📸 by Vitalii Ustymenko)

Angular In Depth

The place where advanced Angular concepts are explained

By Angular In Depth

A newsletter with focus on advanced web development, written and curated by Max Koretskyi and inDepth.dev team. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store