Interface IStreamRequestHandler<TRequest, TItem>
- Namespace
- SimpleMediator
- Assembly
- SimpleMediator.dll
Executes the logic associated with a streaming request using Railway Oriented Programming.
public interface IStreamRequestHandler<in TRequest, TItem> where TRequest : IStreamRequest<TItem>
Type Parameters
TRequestHandled stream request type.
TItemType of each item yielded by the stream.
Examples
public sealed class StreamProductsHandler : IStreamRequestHandler<StreamProductsQuery, Product>
{
public async IAsyncEnumerable<Either<MediatorError, Product>> Handle(
StreamProductsQuery request,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var pageNumber = 0;
while (true)
{
var products = await _repository.GetPageAsync(pageNumber, request.PageSize, cancellationToken);
if (products.Count == 0)
yield break;
foreach (var product in products)
{
if (!product.IsValid)
{
yield return Left(MediatorErrors.ValidationFailed($"Invalid product: {product.Id}"));
continue;
}
yield return Right(product);
}
pageNumber++;
}
}
}
Remarks
Stream handlers produce items asynchronously using IAsyncEnumerable<T>,
enabling efficient processing of large datasets, real-time feeds, and batch operations.
Each item is wrapped in Either<MediatorError, TItem> to maintain Railway
Oriented Programming semantics. Handlers can yield errors mid-stream without terminating
the sequence, allowing partial results and graceful degradation.
Use yield return Right(item) for successful items and yield return Left(error)
for errors. The consumer decides whether to continue or terminate on errors.
Always use [EnumeratorCancellation] attribute on the cancellation token parameter
to ensure proper cancellation when iteration stops early.
Methods
Handle(TRequest, CancellationToken)
Processes the incoming stream request and yields a sequence of results.
IAsyncEnumerable<Either<MediatorError, TItem>> Handle(TRequest request, CancellationToken cancellationToken)
Parameters
requestTRequestStream request to handle.
cancellationTokenCancellationTokenCancellation token that triggers when iteration stops or times out. Must be decorated with
[EnumeratorCancellation]attribute.
Returns
- IAsyncEnumerable<Either<MediatorError, TItem>>
Async enumerable of
Either<MediatorError, TItem>, where each element represents either an error (Left) or a successful item (Right).
Remarks
Use static LanguageExt.Prelude to access Left and Right factory methods.
Unlike regular handlers, stream handlers do NOT short-circuit on errors - errors are yielded
as part of the stream, and the consumer decides whether to continue or stop.
Always check cancellationToken.IsCancellationRequested before expensive
operations, especially when fetching additional pages or performing I/O.
When implementing this interface, decorate the cancellation token parameter with
[EnumeratorCancellation] attribute to ensure proper cancellation when iteration stops early.