Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Forked from omerfarukz/EventAggregator.cs
Last active August 29, 2015 14:06
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 yemrekeskin/0331541097ad6bc6ef3f to your computer and use it in GitHub Desktop.
Save yemrekeskin/0331541097ad6bc6ef3f to your computer and use it in GitHub Desktop.
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);
}
}
}
}
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