Skip to content

Instantly share code, notes, and snippets.

@brainwipe
Created May 16, 2020 06:17
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 brainwipe/cad633a2d45f136cd092c85b8bd5fcba to your computer and use it in GitHub Desktop.
Save brainwipe/cad633a2d45f136cd092c85b8bd5fcba to your computer and use it in GitHub Desktop.
A fail-fast lightweight event Event Aggregator for Pub/Sub
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