使用IMvxMessenger两次获取Messege [英] Getting Messege Twice Using IMvxMessenger
问题描述
我正在使用Xamrin Android应用程序,并且正在使用MvvmCross.在我的应用程序中,我使用了IMvxMessenger.但是当我更改视图并返回到同一视图时,我两次都收到消息. 解决办法是什么 ? 这是我的代码: 在ViewModel中,我有以下代码:
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);
}
推荐答案
视图(无论是活动还是片段)始终被创建和销毁.由于您要订阅 OnCreateView(),因此应该取消订阅 OnDestroyView().
Views (whether Activities or Fragments) are created and destroyed all the time. Since you are subscribing in OnCreateView(), you should unsubscribe in OnDestroyView().
可能发生的事情是 OnCreateView()被多次调用并导致添加多个订阅. MvxMessenger 正在向所有订户广播该消息.如果View被销毁但尚未取消订阅,则由于回调不再存在,很有可能会崩溃.
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.
这篇关于使用IMvxMessenger两次获取Messege的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!