06 Streaming - vagnerjsmello/NexMediator GitHub Wiki

๐Ÿ“ก Streaming with INexStreamRequest

NexMediator supports streaming responses using IAsyncEnumerable<T> through the interface INexStreamRequest<T>.

This is useful for:

  • Long-running queries
  • Server push scenarios
  • UI updates that consume live streams

๐Ÿงฉ What is INexStreamRequest?

It works like a query, but instead of returning a single result, it returns a stream of values asynchronously.

๐Ÿ“ฆ Example: StreamAuctionsEndingSoon

This example streams auctions that will end in the next 48 hours, ordered by EndDate.

public record StreamAuctionsEndingSoon() : INexStreamRequest<AuctionSummaryDto>;
public class StreamAuctionsEndingSoonHandler : INexStreamRequestHandler<StreamAuctionsEndingSoon, AuctionSummaryDto>
{
    private readonly IAuctionRepository _repository;

    public StreamAuctionsEndingSoonHandler(IAuctionRepository repository)
    {
        _repository = repository;
    }

    public async IAsyncEnumerable<AuctionSummaryDto> Handle(StreamAuctionsEndingSoon request, [EnumeratorCancellation] CancellationToken ct)
    {
        var now = DateTime.UtcNow;
        var auctions = await _repository.GetEndingSoonAsync(now.AddHours(48), ct);

        foreach (var auction in auctions.OrderBy(a => a.EndDate))
        {
            yield return new AuctionSummaryDto(auction.Id, auction.BoardGame.Title, auction.EndDate);
            await Task.Delay(50, ct); // simulate streaming delay
        }
    }
}

๐Ÿงช DTO used

public record AuctionSummaryDto(Guid Id, string Title, DateTime EndDate);

๐Ÿงฌ Sample usage in controller

await foreach (var auction in nexMediator.Stream(new StreamAuctionsEndingSoon(), ct))
{
    Console.WriteLine($"Auction: {auction.Title} | Ends at: {auction.EndDate}");
}

๐Ÿง  Notes

  • Stream requests are great for UI polling, dashboards, or log exports
  • They are supported natively by NexMediator and do not need special configuration
  • Behaviors like validation or logging still work on streamed handlers

Streaming opens the door for responsive and reactive data flows in your CQRS architecture.

Next step โ†’ ASP.NET Core Integration