Kelson.Common

Collection of packages published under the Kelson.Common namespace

View the Project on GitHub KelsonBall/Kelson.Common

Pub Sub Eventing

Create or inject an event manager for events to be managed by.

// using Kelson.Common.Events;

var events = new EventManager();

To subscribe to an event of a particular type use the .Subscribe method

ISubscription Subscribe(Action action)

class EventArgs
{
    public int Value { get; set; }
}

events.Subscribe<EventArgs>(a => Console.WriteLine(a.Value));

Event types do not need to be custom types

events.Subscribe<int>(value => Console.WriteLine(value));

To publish an event use the .Publish method

void Publish(T payload)

events.Subscribe<int>(value => Console.WriteLine(value));

events.Publish(2);
> 2

events.Subscribe<int>(value => Console.WriteLine(Convert.ToString(value, 2))); // multiple subscriptions to 1 event type

events.Publish(3);
> 2
> "11"
// both subscriptions invoked

Subscriptions create references from the event manager to any objects referenced by the subscription delegate. To allow subscribers to be garbage collected stay a while and .Listen

ISubscription Listen(Action action)

class SubscribingObject
{
    public SubscribingObject(IEventManager events) 
        => events.Listen<int>(v => Console.WriteLine(v));
}

var events = new EventManager();

var item = new SubscribingObject(events);

events.Publish(3);
> 3

item = null;
GC.Collect();

events.Publish(3);
// listener was garbage collected, so no event should be published