SubscribeHell a real performance sink for any Angular application

⚠️ Angular & RxJS Developers

Stop doing this right now.

This is a very common mistake that you need to stop

In my experience, one of the most serious and widespread mistakes in Angular code that I review is the understanding and use of subscribers. More broadly of RxJS in general.

Today I’m talking about the “subscribes hell” 👇🏻

A “subscribes hell” is a design error in the use of observables and their subscriptions leading to major exponential memory leaks.

😥 The super sad thing:

I’ve seen this before….

A visit to a page that adds 20MB to your RAM, for the duration of your session on the site, and as a bonus accumulates and stacks up with each re-visit to the page.
This can quickly reach 1GB of RAM if the user has a long and complete session on the application.

Sometimes we need to aggregate the values of several observables or process nested observables to perform an action.

To do this, we can use one of the combination or flattening operators such as SwitchMap, MergeMap, CombineLatest, etc…

👉🏻 We’ll work with examples, it’s more meaningful for everyone.

Let’s take the Story below 👇

🗣️ As a user of the site, I would like to be able to access the detailed file of a product, in order to obtain all the information.

Here we will need to use ActivatedRoute and ProductService :

  • The first allows us to obtain the product identifier contained in the URL of the route.
  • The 2nd one allows you to get the details of a product from its identifier.

We can clearly guess the link between the two actors, we will have to combine the recovery of the identifier in the URL and the recovery of the product details.

What to stop immediately:

🚫 Nesting the subscribes and thus creating a “subscribes hell”.

What should be implemented now:

✅ Use a combining RxJS operator such as SwitchMap.

💡 BONUS: As we use AsyncPipe the unsubscription handling is delegated and done at the destruction of the component.

👉 GitHub code link

Avatar photo
Nathan Tréhout

Badass Angular developer, Typescript and RxJS addict.

#kubernetes #angular #typescript #rxjs

Articles: 3
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x