1

This question is a follow-up / "second attempt" to a previous question of mine.

I am building a cross-platform mobile application using MvvmCross framework, and I would like to use the Messenger plugin to receive event notifications published from somewhere else in my code.

I have tried to add the subscription in the ctor as follows:

public class MyViewModel : BaseViewModel, IMyViewModel
{
    private MvxSubscriptionToken _showMsgToken;

    public MyViewModel ()
    {
        _showMsgToken = MvxMessenger.Subscribe<ShowMsg>(message => onShowNavigation(), MvxReference.Weak);
    }
    private void onShowNavigation()
    {
        //Do Stuff
    }
}

Now when I navigate to this ViewModel everything works and notifications are received.
However, when I navigate away and back to this ViewModel, I can see that the Subscription is adding another entry to the MvxMessenger subscriptions property, resulting onShowAdsNavigation() firing twice for each new event.

So, How can I subscribe to events in the ViewModel? Or maybe I need to find a way to Unsubscribe from events?

Community
  • 1
  • 1
Liel
  • 2,407
  • 4
  • 20
  • 39

1 Answers1

1

If you need to actively unsubscribe from messages, then you can do this by capturing lifetime events within your views and then using these to drive your viewmodel. This is your code - you can do what you like.

For some options on this, see ViewModel LifeCycle, when does it get disposed?


I generally don't bother with active management of subscriptions. Instead I rely on the fact that the View will be removed from the UI, and so it and its ViewModel will be removed from memory at some time afterwards. When this happens I know that the subscription management will then happen automatically - when the View and ViewModel get Garbage Collected, then the subscriptions will also shortly afterwards get cleaned up. I know that the weak referencing used within the Messenger will mean that the subscriptions will clean themselves up.

To prove this, try https://github.com/slodge/MessengerHacking - it has a button to force GC to occur.

If this isn't "good enough* for your app, then see "If you need to actively..." above.

Community
  • 1
  • 1
Stuart
  • 66,722
  • 7
  • 114
  • 165