Skip to content

Instantly share code, notes, and snippets.

@Larry57
Last active December 21, 2016 11:21
Show Gist options
  • Save Larry57/089a95c4677ce30e7fbd67cf14795418 to your computer and use it in GitHub Desktop.
Save Larry57/089a95c4677ce30e7fbd67cf14795418 to your computer and use it in GitHub Desktop.
My ludicrous and naive attempt to implement another Event hub for .NET : The Most Simple Possible Event Aggregator
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace MSPEventAggregator {
void sample_usage() {
var hub = new MessageHub();
var token = hub.Subscribe<string>(s => Console.Write(s));
hub.Publish("hello");
hub.Unsubscribe(token);
}
public class MessageHub {
ConcurrentDictionary<Type, ConcurrentBag<ISubscription>> subscriptions = new ConcurrentDictionary<Type, ConcurrentBag<ISubscription>>();
public void Publish<T>(T message) {
ConcurrentBag<ISubscription> messageSubscriptions;
if (subscriptions.TryGetValue(typeof(T), out messageSubscriptions))
foreach (Subscription<T> messageSubscription in messageSubscriptions)
messageSubscription.Action(message);
}
public ISubscription Subscribe<T>(Action<T> doThis) {
var subscription = new Subscription<T>(doThis, typeof(T));
var messageSubscriptions = subscriptions.GetOrAdd(typeof(T), new ConcurrentBag<ISubscription>());
messageSubscriptions.Add(subscription);
return subscription;
}
public void Unsubscribe(ISubscription subscription) {
ConcurrentBag<ISubscription> messageSubscriptions;
if (subscriptions.TryGetValue(subscription.MessageType, out messageSubscriptions)) {
messageSubscriptions.TryTake(out subscription);
if (!messageSubscriptions.Any())
subscriptions.TryRemove(subscription.MessageType, out messageSubscriptions);
}
}
}
public class Subscription<T> : ISubscription {
public Subscription(Action<T> action, Type type) {
Action = action;
MessageType = type;
}
public Action<T> Action { get; }
public Type MessageType { get; }
}
public interface ISubscription {
Type MessageType { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment