Tag Archives: Events

Do I really need to unsubscribe every event?

I’ve seen a lot of source code in my life. Some really good code, that I loved to read und understand. My wife loves to read good books, I love to read good source code. 🙂

But sometimes, you read lines of code and think: Why??? Why, is someone doing this??? I remember one code snipped, I’ve seen a couple months ago. I think the developer was afraid of memory leaks, maybe he read an article about events causing memory leaks, when they are not detached.

To summon up the code, it was as simple as that:

A ViewModel_A published an event and ViewModel_B subscribed to it. The guy writing it (I think he tried to “optimize” it..) made both ViewModels IDisposable and ViewModel_B unsubscribed that event. It wasn’t quite clear who actually disposes the objects of ViewModel_B, but that’s another story.

But, do we really have to unsubscribe each event, we ever hook on? Short answer NO! It actually depends on your use case and the lifetime of each objects. ViewModels usually have a short lifetime (as long as you are visiting the page), therefore you don’t normally have to destroy the subscription. (In regular settings, you actually don’t need events within ViewModels, but I will not say never)

So let’s have a look at our sample, with all available connections. We have a View, with ViewModel_A as the BindingContext. The View_A has a ListView with items, each item has ViewModel_B as the BindingContext. And each ViewModel subscribes to the UpdateEvent. (Ok, I made this one up, to be more logical, even though I would probably solve such a setting in a different way).

ModelConnections1

The Garbage Collectors looks through the references, and as long as View_A is somehow in a NavigationStack, or viewed on the screen, everything stays in memory. Let’s say our View_A gets disposed, because the user closes the page (or whatever). Now we have lost all connections, and only the event will keep both ViewModels connected. But all of those ViewModels have no connection to a View anymore, so they are both dead, and the Garbage Collector will sooner or later clean them up.

But are there cases, when I need to tidy up on events?
Yes, definitely, there are some cases. You just have to keep one thing in mind:

The publisher keeps the subscriber alive. Not vice versa.

Let’s say we have a service, which is implemented as a singleton (or instantiated as such in an IOC container). So the object is alive over the whole app lifecycle. When this service publishes an event, and a ViewModel subscribes it, the ViewModel will never get destructed (perhaps some time, when the app terminates). But beware, that just implementing an interface like IDisposable will not solve your problem .. you also need to use it, and think of when you want to dispose your object. Prism has a nice variant for PageViewModels; IDestructible. When you use Prism, just have a look at it, it’ll help you on that decision.

Advertisements