riversong code showcase
This commit is contained in:
13
Source/Riversong/Game/CommonServices/Signals/ISignalBus.cs
Normal file
13
Source/Riversong/Game/CommonServices/Signals/ISignalBus.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
|
||||
namespace DanieleMarotta.RiversongCodeShowcase
|
||||
{
|
||||
public interface ISignalBus
|
||||
{
|
||||
void Raise<T>(T signal);
|
||||
|
||||
void Subscribe<T>(Action<T> handler);
|
||||
|
||||
void Unsubscribe<T>(Action<T> handler);
|
||||
}
|
||||
}
|
||||
31
Source/Riversong/Game/CommonServices/Signals/SignalBus.cs
Normal file
31
Source/Riversong/Game/CommonServices/Signals/SignalBus.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
|
||||
namespace DanieleMarotta.RiversongCodeShowcase
|
||||
{
|
||||
public class SignalBus : ISignalBus, IDisposable
|
||||
{
|
||||
private readonly ListMultiDictionary<Type, Delegate> _subscribers = new();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_subscribers.Clear();
|
||||
}
|
||||
|
||||
public void Raise<T>(T signal)
|
||||
{
|
||||
if (!_subscribers.TryGetValues(typeof(T), out var handlers)) return;
|
||||
|
||||
foreach (var handler in handlers) ((Action<T>)handler).Invoke(signal);
|
||||
}
|
||||
|
||||
public void Subscribe<T>(Action<T> handler)
|
||||
{
|
||||
_subscribers.Add(typeof(T), handler);
|
||||
}
|
||||
|
||||
public void Unsubscribe<T>(Action<T> handler)
|
||||
{
|
||||
_subscribers.Remove(typeof(T), handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user