How to avoid memory leaks while using services communication in Angular ?

Amaury Lapaque
2 min readDec 24, 2020

As you may known, when you want to create a communication between two components there’re a few solutions (https://angular.io/guide/component-interaction) but today we will take a look at the communication between two components without any relation, for this you’ll need to use a service.

In this example, we don’t need to manage the subscription because we are using the Async pipe from Angular

But sometimes we need to subscribe to this BehaviorSubject, for example a simple refresh needed. As there’s nothing linked to this, I need to receive the information that something changed and the other component needs to refresh it’s content.

Here is an example →

test memory leak

As you can see here I’m sending a message, the BehaviorSubject is subscribed emits the value true because I need to refresh my messages. But when I’m destroying the component and spamming the send buttons you can see that the BehaviorSubject is still subscribed and is still emitting → THAT’S A MEMORY LEAK

If the unsubscribe of the BehaviorSubject is not managed by yourself it will cause several performance issues in your application, because of course if you re-instantiate your component it will duplicate the subscription…

So to avoid that, I’ve decided to create a service which will manage this in an easier way.

In a few words, a Map<string,Array<Subscription>> will contains the subscriptions by components and will to a CRUD on it to avoid duplication.

Here is the service with an example on how to use it →

And here is the test →

Hope this will help you in your angular application, if you have any recommendation feel free to contact me by linkedin https://www.linkedin.com/in/amaury-lapaque/

--

--