问题
I am working on Xamrin Android Application and I am using MvvmCross.In my application I have used IMvxMessenger.But I am getting messsge twice when I change the view and comeback to same view.And then It is Crashed. What is the solution ? Here is my code : In ViewModel I have this code :
var messanger = Mvx.Resolve<IMvxMessenger>();
var message = new MyMessage(this,"Product has been added",cartListCount);
messanger.Publish(message);
And On View I have this code:
private MvxSubscriptionToken _token;
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = base.OnCreateView(inflater, container, savedInstanceState);
messenger = Mvx.Resolve<IMvxMessenger>();
_token = messenger.SubscribeOnMainThread<MyMessage>(OnInputIsNeeded,MvxReference.Strong);
return view;
}
private void OnInputIsNeeded(MyMessage _Message)
{
Toast.MakeText (this.Activity,_Message.Message, ToastLength.Short).Show();
messenger.Unsubscribe<MyMessage> (_token);
}
回答1:
Views (whether Activities or Fragments) are created and destroyed all the time. Since you are subscribing in OnCreateView(), you should unsubscribe in OnDestroyView().
What's likely happening is that OnCreateView() is being called multiple times and causing multiple subscriptions to be added. MvxMessenger is broadcasting the message to all subscribers. If a View is destroyed, but hasn't unsubscribed, it's likely to crash since the callback no longer exists.
来源:https://stackoverflow.com/questions/32694275/getting-messege-twice-using-imvxmessenger