Skip to content

Instantly share code, notes, and snippets.

@geirsagberg
Created September 24, 2015 08:31
Show Gist options
  • Save geirsagberg/616d25be9aa20a09ad05 to your computer and use it in GitHub Desktop.
Save geirsagberg/616d25be9aa20a09ad05 to your computer and use it in GitHub Desktop.
MvvmCross SubscriptionManager
public class SubscriptionManager
{
private Dictionary<Type, MvxSubscriptionToken> subscriptions = new Dictionary<Type, MvxSubscriptionToken>();
public IMvxMessenger Messenger { get; set; }
public SubscriptionManager(IMvxMessenger messenger)
{
Messenger = messenger;
}
public void SubscribeToMessage<T>(Action<T> action) where T : MvxMessage
{
Unsubscribe<T>();
subscriptions[typeof (T)] = Messenger.SubscribeOnMainThread(action);
}
/// <summary>
/// Subscribes to a message and automatically unsubscribes after the first message is received.
/// </summary>
public void SubscribeToSingleMessage<T>(Action<T> action) where T : MvxMessage
{
SubscribeToMessage<T>(t => {
Unsubscribe<T>();
action(t);
});
}
private void Unsubscribe<T>() where T : MvxMessage
{
var type = typeof (T);
MvxSubscriptionToken value;
if (subscriptions.TryGetValue(type, out value))
Messenger.Unsubscribe<T>(value);
}
public void UnsubscribeAll()
{
var unsubscribeMethod = typeof (IMvxMessenger).GetRuntimeMethod("Unsubscribe",
new[] { typeof (MvxSubscriptionToken) });
foreach (var pair in subscriptions) {
var genericMethod = unsubscribeMethod.MakeGenericMethod(pair.Key);
genericMethod.Invoke(Messenger, new object[] { pair.Value });
}
subscriptions = new Dictionary<Type, MvxSubscriptionToken>();
Messenger.RequestPurgeAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment