Skip to content

Instantly share code, notes, and snippets.

@mikoskinen
Created February 18, 2017 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikoskinen/935608835f27e6d8ecbe63483709ddf1 to your computer and use it in GitHub Desktop.
Save mikoskinen/935608835f27e6d8ecbe63483709ddf1 to your computer and use it in GitHub Desktop.
Simple Event Aggegator for Multi Window communication in UWP
public interface ISubscriber<in TMessage>
{
void HandleMessage(TMessage message);
}
public class MyEventAggregator
{
private static List<Tuple<CoreDispatcher, object>> subscribers = new List<Tuple<CoreDispatcher, object>>();
public void Subscribe<TMessage>(ISubscriber<TMessage> subscriber)
{
subscribers.Add(new Tuple<CoreDispatcher,object>(Window.Current.Dispatcher, subscriber));
}
public void Publish<TMessage>(TMessage message)
{
var messageType = GetEventType(message);
foreach (var subscriber in subscribers)
{
var handler = subscriber.Item2;
if (messageType.IsInstanceOfType(handler))
{
var dispatcher = subscriber.Item1;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
((ISubscriber<TMessage>)handler).HandleMessage(message);
});
}
}
}
private static Type GetEventType<T>(T args)
{
return typeof(ISubscriber<>).MakeGenericType(args.GetType());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment