Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jpmikkers/baksteen.async.modernevents
ModernEvents are async capable events that support both sync and async subscribers
https://github.com/jpmikkers/baksteen.async.modernevents
async csharp csharp-library dotnet events observable publish-subscribe
Last synced: about 1 month ago
JSON representation
ModernEvents are async capable events that support both sync and async subscribers
- Host: GitHub
- URL: https://github.com/jpmikkers/baksteen.async.modernevents
- Owner: jpmikkers
- License: mit
- Created: 2024-04-19T10:36:32.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2024-05-02T10:26:59.000Z (7 months ago)
- Last Synced: 2024-10-12T14:21:16.697Z (about 1 month ago)
- Topics: async, csharp, csharp-library, dotnet, events, observable, publish-subscribe
- Language: C#
- Homepage:
- Size: 101 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Baksteen.Async.ModernEvents
ModernEvents are async capable events that support both sync and async subscribers. This implementation is modeled more or less after [David Fowler](https://twitter.com/davidfowl)'s tweet [here](https://x.com/davidfowl/status/1766566736864891192?t=f-FMCheU28EbG3c9JV-5pQ&s=35)
## Usage
On the producer side, we have to expose a `IModernEvent` property:
```csharp
using Baksteen.Async.ModernEvents
...public class ExampleWithModernEvents
{
// example event argument record
public record ClientAddedArgs(string Name);// privately declare a concrete ModernEvent field
private ModernEvent _clientAddedEvent = new();// publicly only expose the IModernEvent interface
public IModernEvent OnClientAdded { get => _clientAddedEvent; }public async Task AddClient(string newClientName)
{
// add client to database
...// notify all (sync & async) subscribers
await _clientAddedEvent.InvokeAsync(new ClientAddedArgs{ Name = newClientName });
}
}
```
\
On the consumer side, subscribing then looks as follows:```csharp
var clientRegistry = new ExampleWithModernEvents();// sync subscription:
clientRegistry.OnClientAdded.Subscribe(args =>
Console.WriteLine($"Client {args.Name} was added"));// async subscription:
clientRegistry.OnClientAdded.Subscribe(async args => {
Console.WriteLine($"Client {args.Name} was added");
await Task.CompletedTask; });
```
\
The `Subscribe()` method returns a `IDisposable` so the consumer can unsubscribe from the event:```csharp
var clientRegistry = new ExampleWithModernEvents();// async subscription:
var subscription = clientRegistry.OnClientAdded.Subscribe(async args => {
Console.WriteLine($"Client {args.Name} was added");
await Task.CompletedTask; });// events will be received here
subscription.Dispose();
// we're no longer subscribed here
```