Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvvmCross Messenger Plugin Purging subscriptions

Tags:

mvvmcross

I'm using the Messenger Plugin in my MvvmCross application and have noticed that it sometimes purges my subscriptions ("One or more listeners failed - purge scheduled"). This is causing an error in my application. By default I am using the weak reference for the subscriptions and I am not unsubscribing from the message.

Do I need to be Unsubscribing? Isn't the point of a weak reference to allow it to be garbage collected?

My BaseView is subscribing in the constructor as shown below.

 public BaseView()
    {
        _messenger = Mvx.Resolve<IMvxMessenger>();
        _messenger.Subscribe<MyMessage>(s => Method());
    }

Below is my Broadcast Receiver publishing my message.

 var _messenger = Mvx.Resolve<IMvxMessenger>();
 _messenger.Publish<MyMessage>(new MyMessage(this));

I have an idea of trying to unsubscribe in the onDestroy.

If you could give me some insight as to why this is happening and a possible resolution I would be grateful.

Thanks in advance.

like image 207
Jake Avatar asked Oct 29 '13 09:10

Jake


1 Answers

When using weak references, it's important to store the returned subscription token in a class-level field.

private IDisposable _token;

public BaseView()
{
    _messenger = Mvx.Resolve<IMvxMessenger>();
    _token = _messenger.Subscribe<MyMessage>(OnMyMessage);
}

private void OnMyMessage(MyMessage msg)
{
   // code
}

If you don't do this, then the GarbageCollector is free to collect the subscription.

For more on this, please see the section on "This GC-based unsubscription will occur whenever the subscription token returned from Subscribe is Garbage Collected" in the wiki - https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#messenger

like image 60
Stuart Avatar answered Oct 01 '22 02:10

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!