To prevent memory leaks in your views, every event you subscribed to needs to be unsubscribed from, either way using WeakSubscribe
or subscribing to events as usual.
A common scenario would be subscribing on:
- Android
OnResume()
- iOS
ViewWillAppear()
then dispose the subscription on:
- Android
OnPause()
- iOS
ViewWillDisappear()
WeakSubscribe
If you want to "listen" for ViewModel property changes, WeakSubscribe
comes in handy:
private IDisposable _selectedItemToken;
_selectedItemToken = ViewModel.WeakSubscribe(() =>
ViewModel.SelectedItem, (sender, eventArgs) => {
// do something
});
Just notice that WeakSubscribe()
returns an MvxWeakEventSubscription that is also IDisposable
. You need to save a reference to that subscription in your view and dispose it when thew view is no longer needed.
There are two reasons to keep that reference:
- You can dispose it later
- If you don´t keep it, your lambda event handler may not always work
Later on...
_selectedItemToken?.Dispose();
Normal event subscription
If you just need to subscribe to another kind of event (not property changes) in your ViewModel, you don´t actually need WeakSubscribe
. You can just add an event listener to the ViewModel, as you would do with any object.
ViewModel.AnEvent += YourDelegate;
Later on...
ViewModel.AnEvent -= YourDelegate;
Don´t forget the last step. That will prevent memory leaks. As I said, Android OnPause()
and iOS ViewWillDisappear()
are good places to do it.
That way your ViewModel won´t be stuck in memory when the view is disposed thus your view can be garbage collected correctly.