Created
May 16, 2020 06:17
-
-
Save brainwipe/cad633a2d45f136cd092c85b8bd5fcba to your computer and use it in GitHub Desktop.
A fail-fast lightweight event Event Aggregator for Pub/Sub
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 System.Collections; | |
using System.Collections.Generic; | |
// From https://www.youtube.com/channel/UCHg8bDmXIYKAwvyc4yMGuUw | |
namespace Lang.Utility | |
{ | |
public interface IEvent {} | |
public class EventAggregator | |
{ | |
static EventAggregator instance; | |
public static EventAggregator Instance | |
{ | |
get | |
{ | |
if (instance == null) instance = new EventAggregator(); | |
return instance; | |
} | |
} | |
private readonly IDictionary<Type, IList<Action<IEvent>>> subscriptions = new Dictionary<Type, IList<Action<IEvent>>>(); | |
public void Publish<T>(T eventContext) | |
where T : IEvent | |
{ | |
var myEventType = typeof(T); | |
if(subscriptions.ContainsKey(myEventType)) | |
{ | |
foreach(var action in subscriptions[myEventType]) | |
{ | |
action(eventContext); | |
} | |
} | |
} | |
public void Subscribe<T>(Action<T> action) | |
where T : IEvent | |
{ | |
var myEventType = typeof(T); | |
if (!subscriptions.ContainsKey(myEventType)) | |
{ | |
subscriptions.Add(myEventType, new List<Action<IEvent>>()); | |
} | |
subscriptions[myEventType].Add(x => action((T)x)); | |
} | |
} | |
} | |
// Usage | |
public class TestAggregator | |
{ | |
public void Test() | |
{ | |
EventAggregator.Instance.Subscribe<MyEvent>(MyCallBack); | |
EventAggregator.Instance.Publish(new MyEvent()); | |
} | |
void MyCallBack(MyEvent context) | |
{ | |
// Do your work | |
} | |
public class MyEvent : IEvent {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment