I am building a cross-platform mobile application using MvvmCross
framework.
Since I would like to share information between ViewModels, I am registering notifications inside the ViewModel's constructor, using the built in MvxMessenger
.
Let's assume a message named ShowAdsMsg
, and then the ViewModel looks as follows:
public class AdsViewModel : BaseLookersViewModel, IAdsViewModel
{
private MvxSubscriptionToken _showAdsMsgToken;
public AdsViewModel()
{
_showAdsMsgToken = MvxMessenger.Subscribe<ShowAdsMsg>(message => onShowAdsNavigation(), MvxReference.Weak);
MyMessenger.PublishLastMessage();
}
private void onShowAdsNavigation()
{
//Do Stuff
}
}
About the MyMessenger
thing:
The actual navigation to the ViewModel is performed from MainViewModel
.
Since that at the very moment of the navigation itself the AdsViewModel
does not exist yet, messages published from the MainViewModel
cannot reach it.
So, my idea was to naively "remember" the message and publish it when the new ViewModel is ready.
So now the navigation call from the MainViewModel
looks like that:
private void navigate()
{
MyMessenger.RememberMessage(new ShowAdsMsg(this));
ShowViewModel<AdsViewModel>( );
}
I am now able to navigate to the ViewModel, and all the notifications are successfully caught.
However...
When I press the BACK button on the device and re-navigate to the same ViewModel,
The constructor is being called again, and so the message subscription re-occur.
As a result, when a message arrives the onShowAdsNavigation()
handler is being fired twice!
I found this similar post, discussing the question of how to properly dispose a ViewModel,
but it does not contain a direct solution to my problem.
What I need is a solution. It can be either one of the following:
- Idea how Not to subscribe to messages on the ViewModel's ctor.
- Guidance about how and when to correctly dispose the ViewModel.
- Explanation on why the constructor is being called again, and how to avoid that.
- A complete different approach to ViewModel information messaging.
Thanks in advance for you help!
Edit: I found this SO Answer, which basically answers item number 3 in the list above. Still, I am wondering what approach should I take regarding the messenger issue.
Another Edit: I verified that the same behavior exists with MvvmCross tutorial N-05-MultiPage. I simply added a ctor to SecondViewModel, and I hit a breakpoint inside it after each BACK+Renavigate.