Created
May 30, 2025 01:45
-
-
Save jpd21122012/9209597caef88ef9d5c47c1e91bb273b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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