Getting Messege Twice Using IMvxMessenger

断了今生、忘了曾经 提交于 2019-12-10 18:55:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!