Created
February 18, 2017 10:33
-
-
Save mikoskinen/935608835f27e6d8ecbe63483709ddf1 to your computer and use it in GitHub Desktop.
Simple Event Aggegator for Multi Window communication in UWP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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