Why It’s Important to Unsubscribe from RxJS Subscription
In this article, we’ll learn why it’s important to clean our subscriptions. Let’s set up a realistic Angular example.
First, we’ll create a simple Akita store that holds one property:
Great. Now let’s create two components. The first component will listen to the someProp
store’s key and the second component will update it.
# Problem One — Memory Leak
The subscription function holds a reference to this
(the component instance) therefore the PageOne
instance isn’t available for garbage collection and will not be collected.
Let’s view it in Chrome dev-tools:
As you can see, the component instance is still in memory even though Angular destroyed it.
# Problem Two — Unexpected Behaviour
Let’s say we need to call the detectChanges()
method upon someProp
update.
Now, let’s move to PageTwoComponent
, update the store and see what’s happening.
We didn’t clean up our subscription function before Angular destroyed the component, so when we update the store, it runs and calls the detectChanges()
method on a component that from Angular perspective is destroyed.
The Solution
In one word — Unsubscribe 😀.
Let’s see that we clean the memory leak and everything is working as expected.
It’s worth mention that everything is also relevant to event emitters, intervals, timers, etc.
😍 Have You Tried Akita Yet?
One of the leading state management libraries, Akita has been used in countless production environments. It’s constantly developing and improving.
Whether it’s entities arriving from the server or UI state data, Akita has custom-built stores, powerful tools, and tailor-made plugins, which help you manage the data and negate the need for massive amounts of boilerplate code. We/I highly recommend you try it out.
Follow me on Medium or Twitter to read more about Angular, Akita and JS!