Skip to content

Instantly share code, notes, and snippets.

@mikebridge
Last active March 10, 2021 02:28
Show Gist options
  • Save mikebridge/f6799ebed20160f72a3daf62f584d2ff to your computer and use it in GitHub Desktop.
Save mikebridge/f6799ebed20160f72a3daf62f584d2ff to your computer and use it in GitHub Desktop.
A simple Event Aggregator that allows multiple subscribers per message type.
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
// inspired by https://github.com/shiftkey/Reactive.EventAggregator/blob/master/src/Reactive.EventAggregator/EventAggregator.cs
namespace Messaging
{
public interface IEventAggregator : IDisposable
{
IDisposable Subscribe<T>(Action<T> action); //where T : IDomainEvent;
void Publish<T>(T @event); //where T : IDomainEvent;
}
public class EventAggregator : IEventAggregator
{
readonly Subject<object> _subject = new Subject<object>();
public IDisposable Subscribe<T>(Action<T> action)
{
return _subject.OfType<T>()
.AsObservable()
.Subscribe(action);
}
public void Publish<T>(T sampleEvent)
{
_subject.OnNext(sampleEvent);
}
public void Dispose()
{
_subject.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment