Last active
July 28, 2021 00:34
-
-
Save TBertuzzi/36ac20fe411469c1efdce063a8ddd645 to your computer and use it in GitHub Desktop.
EventAggregator
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading; | |
namespace XamarinFormsEventAggregator.Events | |
{ | |
public class EventAggregator : IEventAggregator | |
{ | |
private readonly List<Delegate> _handlers = new List<Delegate>(); | |
private readonly SynchronizationContext _synchronizationContext; | |
public EventAggregator() | |
{ | |
_synchronizationContext = SynchronizationContext.Current; | |
} | |
public void SendMessage<T>(T message) | |
{ | |
if (message == null) | |
{ | |
return; | |
} | |
if (_synchronizationContext != null) | |
{ | |
_synchronizationContext.Send( | |
m => Dispatch<T>((T)m), | |
message); | |
} | |
else | |
{ | |
Dispatch(message); | |
} | |
} | |
public void PostMessage<T>(T message) | |
{ | |
if (message == null) | |
{ | |
return; | |
} | |
if (_synchronizationContext != null) | |
{ | |
_synchronizationContext.Post( | |
m => Dispatch<T>((T)m), | |
message); | |
} | |
else | |
{ | |
Dispatch(message); | |
} | |
} | |
public Action<T> RegisterHandler<T>(Action<T> eventHandler) | |
{ | |
if (eventHandler == null) | |
{ | |
throw new ArgumentNullException("eventHandler"); | |
} | |
_handlers.Add(eventHandler); | |
return eventHandler; | |
} | |
public void UnregisterHandler<T>(Action<T> eventHandler) | |
{ | |
if (eventHandler == null) | |
{ | |
throw new ArgumentNullException("eventHandler"); | |
} | |
_handlers.Remove(eventHandler); | |
} | |
private void Dispatch<T>(T message) | |
{ | |
if (message == null) | |
{ | |
throw new ArgumentNullException("message"); | |
} | |
var compatibleHandlers | |
= _handlers.OfType<Action<T>>() | |
.ToList(); | |
foreach (var handler in compatibleHandlers) | |
{ | |
handler(message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment