Skip to content

Instantly share code, notes, and snippets.

@jpd21122012
Created May 30, 2025 01:45
Show Gist options
  • Save jpd21122012/9209597caef88ef9d5c47c1e91bb273b to your computer and use it in GitHub Desktop.
Save jpd21122012/9209597caef88ef9d5c47c1e91bb273b to your computer and use it in GitHub Desktop.
public class EventStream<T>
{
private event Action<T> _eventStream;
public IDisposable Subscribe(Action<T> observer)
{
_eventStream += observer;
return new Disposable(() => _eventStream -= observer);
}
public void Publish(T data)
{
_eventStream?.Invoke(data);
}
private class Disposable : IDisposable
{
private readonly Action _disposeAction;
public Disposable(Action disposeAction)
{
_disposeAction = disposeAction;
}
public void Dispose()
{
_disposeAction?.Invoke();
}
}
}
// Usage
var stream = new EventStream<string>();
var subscription = stream.Subscribe(msg => Console.WriteLine($"Received: {msg}"));
stream.Publish("Hello, Reactive World!");
subscription.Dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment