Last active
April 7, 2019 22:33
-
-
Save scionwest/d504784ebbaca261aec9137b5795f346 to your computer and use it in GitHub Desktop.
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 Connection | |
{ | |
Socket connection; | |
IPublisher publisher; | |
public Connection(IPublisher publisher, Socket connection) | |
{ | |
this.publisher = publisher; | |
this.connection = connection; | |
} | |
void Listen() | |
{ | |
while(connection.IsConnected) | |
{ | |
var buffer = connection.Receive(); | |
var data = buffer.ConvertToData(); //extension | |
this.publisher.Publish(new WorldTimeChanged(data)); | |
} | |
} | |
{ | |
public class Publisher : IPublisher | |
{ | |
private readonly ConcurrentDictionary<Type, List<ISubscription>> listeners = | |
new ConcurrentDictionary<Type, List<ISubscription>>(); | |
ISubscription Subscribe<TMessageType>(Action<TMessageType, ISubscription> callback, Func<TMessageType, bool> condition = null) | |
{ | |
this.listeners.TryAdd(typeof(TMessageType), new List<ISubscription>()); | |
List<ISubscription> subscribers = listeners[messageType]; | |
var handler = new Notification<TMessageType>(); | |
handler.Register(callback, condition); | |
subscribers.Add(handler); | |
} | |
void Publish<T>(T message) | |
{ | |
var listenersToPublishTo = this.listeners[typeof(T)].OfType<Notification<T>>().ToArray(); | |
foreach (Notification<T> handler in listenersToPublishTo) | |
{ | |
handler.ProcessMessage(message); | |
} | |
} | |
} | |
public class World | |
{ | |
IPublisher publisher; | |
public World(IPublisher publisher) => this.publisher = publisher; | |
public double WorldTime {get; private set;} | |
// Initialized on the main thread | |
void Initialize() | |
{ | |
publisher.Subscribe<WorldTimeChanged>((message, sub) => this.WorldTime = message.NewTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment