Created
March 16, 2019 18:59
-
-
Save StefanoFiumara/c958201a2447b71fbe55fa3e11c81508 to your computer and use it in GitHub Desktop.
Simple Event Aggregator
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 class EventAggregator | |
{ | |
private readonly Dictionary<string, IList<Action<object>>> _events; | |
public EventAggregator() | |
{ | |
_events = new Dictionary<string, IList<Action<object>>>(); | |
} | |
public void Subscribe(string eventKey, Action<object> handler) | |
{ | |
if (!_events.ContainsKey(eventKey)) | |
{ | |
_events[eventKey] = new List<Action<object>> {handler}; | |
} | |
else | |
{ | |
_events[eventKey].Add(handler); | |
} | |
} | |
public void Unsubscribe(string eventKey, Action<object> handler) | |
{ | |
if (!_events.ContainsKey(eventKey)) return; | |
while (_events[eventKey].Contains(handler)) | |
{ | |
_events[eventKey].Remove(handler); | |
} | |
} | |
public void Publish(string eventKey, object args) | |
{ | |
if (!_events.ContainsKey(eventKey)) return; | |
foreach (var action in _events[eventKey]) | |
{ | |
action?.Invoke(args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment