-
-
Save yemrekeskin/0331541097ad6bc6ef3f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
namespace OMR.Core.Helpers | |
{ | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class EventAggregator | |
{ | |
public IDictionary<Type, IList> Subscribers; | |
public EventAggregator () | |
{ | |
Subscribers = new Dictionary<Type, IList> (); | |
} | |
public void Publish<T> (T instance) | |
{ | |
IList actions; | |
Subscribers.TryGetValue (typeof(T), out actions); | |
if (actions != null) { | |
foreach (Action<T> item in actions) { | |
item (instance); | |
} | |
} | |
} | |
public void Subscribe<T> (Action<T> action) | |
{ | |
if (Subscribers.ContainsKey (typeof(T))) { | |
Subscribers [typeof(T)].Add (action); | |
} else { | |
Subscribers.Add (typeof(T), new List<Action<T>> () { action }); | |
} | |
} | |
public void UnSubscribe<T> (Action<T> action) | |
{ | |
IList actions; | |
Subscribers.TryGetValue (typeof(T), out actions); | |
if (actions != null) { | |
actions.Remove (action); | |
} | |
} | |
} | |
} |
This file contains hidden or 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
using System; | |
using OMR.Core.Helpers; | |
namespace event_aggregator_sample | |
{ | |
class MainClass | |
{ | |
public static void Main (string[] args) | |
{ | |
var ea = new EventAggregator(); | |
ea.Subscribe<int>(onEventRaised); | |
ea.Publish<int>(1); | |
ea.UnSubscribe<int>(onEventRaised); | |
ea.Publish<int>(1); | |
Console.ReadKey(); | |
} | |
public static void onEventRaised(int i) | |
{ | |
Console.WriteLine("Event raised with value of " + i); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment