1. 程式人生 > >Why It’s Important to Unsubscribe from RxJS Subscription

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.

?? Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment for over seven months, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

Follow me on Medium or Twitter to read more about Angular, Akita and JS!