MvxMessenger and Subscription Hell

MessengerBus allows your application to subscribe and publish events form different parts of your application while giving you the flexibility of a loosely coupled architecture.

MvvmCross provides its own built in Event aggregation Messenger: MvxMessenger with the twist that it is implemented using WeakReferences. (I talked more about WeakReferences in my Post about Memory and Performance.) In short, WeakReferences helps in preventing Strong object references thus reducing memory leaks; making it the best contender tool of its kinds for mobile apps.

MvxMessenger is easy to integrate in your application, however its use is intricate and often leads users to bugs that they are not expecting.

“My View is no longer visible on screen but I keep getting subscription notifications in my ViewModel”

This is a recurring question I get from developers. First, If you read my blog post about avoiding memory performance issues with Xamarin, this shouldn’t be happening to you. One of the beauties of the MvvmCross framework is that fact that it promises all the viewlifecycle calls to your ViewModel, this you should be using the `ViewWillAppear` and `ViewWillDisappear` respectively to subscribe and unsubscribe events.

You may ask, “MvvmCross uses WeakReferences, why am is my ViewModel still receiving notifications even when the View is disposed?“

If this question popped up in your mind, good job! In fact, iOS or and Android will usually dispose views when it is no longer part of the View hierarchy or Navigation Stack as long as there are no strong references preventing the OS from doing so.

Trick: Since all Native objects implements the IDisposable Interface in Xamarin, a trick I have used throughout the years to is to override the Dispose() method and log that the view is effectively being disposed. This allows you to know when a View is retained in memory by just looking at your console logs while debugging.

However, the View being disposed does not guarantee that its associated ViewModel is also disposed. iOS has its own Garbage collection strategy, on top of that Xamarin has its own algorithms to determine when objects should be disposed as part of its runtime. That said, you ViewModel may still be in memory while it is scheduled to be disposed.

The #1 rule that will prevent your form a lot of headaches is to Always make sure your subscription tokens are disposed when you no longer need them.

Happy coding!