Case
I have a ViewModel that lives for the lifespan of the app.
When a given feature is turned on, I subscribe to a given MessagingCenter
message.
When the feature is turned off, I unsubscribe.
{repeat}
Seems simple enough.
Problem
Despite the unsubscribing the handler for the subscription is getting called once for every .Subscribe
taking place. As if the .Unsubscribe
isn't doing its job.
Test
In a fit of desperation I even tried to .Unsubscribe
10 times using both overloads of the method. If there is not subscription existing then no-harm-no-foul, right?
Yet the multiple handling of the single incoming message still happens. Anyone else run across this?
It seems related to, but not identical as, this thread... For one thing, I'm not disposing of either the View or the ViewModel - so there shouldn't be an orphaned subscription hanging out there. this
is always the same instance of this
in other words.
https://forums.xamarin.com/discussion/20420/messagingcenter-causing-problems-if-unsubscribing-within-message-handler
I didn't want to hijack that thread for a new issue.
@JohnMiller You wrote the nice article on unsubscribing... Any thoughts?
Desperation code
I really figure that 10 times the unsubscribes for every subscribe would stop this. Alas, no.
Keep in mind, this is in addition to unsubscribing when the feature gets turned off. Just to be safe/robust/cover all the bases/find anything that works.
MessagingCenter.Unsubscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Unsubscribe<SettingsManager>(this, nameof(SettingsUpdatedMessage));//Avoid duplicate subscriptions
MessagingCenter.Subscribe<SettingsManager, SettingsUpdatedMessage>(this, nameof(SettingsUpdatedMessage), (sender, args) =>
{
OnSettingsChanged();
});