Skip to main content

API Reference

Quick reference for all public types in com.fajrbahr.mediatork.

SubpackageContents
com.fajrbahr.mediatorkCore: Mediator, Request, StreamRequest, HandlerRegistry, MediatorFactory, MediatorException hierarchy
com.fajrbahr.mediatork.handlerRequestHandler, StreamRequestHandler, FallbackRequestHandler (otherwise), Sender, trySend
com.fajrbahr.mediatork.notificationNotification, NotificationHandler, FallbackNotificationHandler (otherwise), all publisher implementations, ThrowMissingNotificationHandler, SilentMissingNotificationHandler
com.fajrbahr.mediatork.pipelinePipelineBehavior, Stage, StreamPipelineBehavior and all built-in behaviors (logging, caching, timeout, timing, error tracking, request counter)
com.fajrbahr.mediatork.validatorRequestValidator, ValidationBehavior, ValidationResult, ValidationException, rules, rulesFailFast

Core interfaces

Request<out TResponse>

Marker interface for requests. Implement to declare a message that expects exactly one handler.

interface Request<out TResponse>

Nested type:
Request.Unit — convenience marker for commands that return no value. Equivalent to Request<Unit>.


RequestHandler<TRequest, TResult> · com.fajrbahr.mediatork.handler

Handles a specific Request type.

interface RequestHandler<in TRequest : Request<TResult>, TResult> {
suspend fun handle(mediator: Mediator, requestContext: RequestContext, request: TRequest): TResult
}

StreamRequest<T>

Marker interface for requests that return a lazy Flow<T> instead of a single value. Dispatch via Mediator.stream().

interface StreamRequest<out T>

Use when the response is a sequence produced over time — large result sets, live feeds, cursor-based exports, or anything better consumed incrementally than batched into a list.


StreamRequestHandler<TRequest, T> · com.fajrbahr.mediatork.handler

Handles a StreamRequest and returns a cold Flow<T>. The interface is not suspend — it returns the flow immediately; work begins when the caller collects it.

interface StreamRequestHandler<in TRequest : StreamRequest<T>, T> {
fun handle(mediator: Mediator, requestContext: RequestContext, request: TRequest): Flow<T>
}
// Define
data class StreamInvoicesQuery(val status: InvoiceStatus? = null) : StreamRequest<Invoice>

// Handle
class StreamInvoicesHandler(private val repo: InvoiceRepository)
: StreamRequestHandler<StreamInvoicesQuery, Invoice> {
override fun handle(mediator: Mediator, requestContext: RequestContext, request: StreamInvoicesQuery): Flow<Invoice> =
repo.all().asFlow().let { flow ->
if (request.status != null) flow.filter { it.status == request.status } else flow
}
}

// Dispatch
mediator.stream(StreamInvoicesQuery(status = InvoiceStatus.APPROVED)).collect { invoice -> ... }

IStreamRequest

Capability for dispatching a StreamRequest to its handler. Implemented by Mediator.

interface IStreamRequest {
fun <TRequest : StreamRequest<T>, T> stream(request: TRequest): Flow<T>
}

stream() is non-suspend. It resolves the handler and returns a cold Flow immediately. Each collection starts a fresh RequestContext.


Notification · com.fajrbahr.mediatork.notification

Marker interface for broadcast events with no response.

interface Notification

NotificationHandler<T> · com.fajrbahr.mediatork.notification

Reacts to a Notification. Multiple handlers per notification type are allowed.

interface NotificationHandler<in T : Notification> {
suspend fun handle(notification: T)
}

PipelineBehavior · com.fajrbahr.mediatork.pipeline

Cross-cutting decorator that wraps each request pipeline.

MemberTypeDefaultDescription
stageStageStage.DefaultAbsolute position group: Pre, Default, or Post
orderInt0Position within the stage; lower = outermost
isEnabledBooleantrueSkip entirely when false
appliesTo(request)BooleantrueOpt out for specific request types
process(ctx, next, req)suspend TResultCore implementation; must call next(request) to continue the chain

Stage

Controls the absolute position of a PipelineBehavior in the chain.

ValuePosition
Stage.PreOutermost wrappers
Stage.DefaultMiddle (default)
Stage.PostInnermost wrappers

Stage always beats order. See Pre / Post Behaviors.


Registry & factory

HandlerRegistry

Stores all registered handlers. Populated by MediatorRegistrar implementations.

MethodDescription
register(handler)Register a request handler (infix, reified)
registerStream(handler)Register a stream request handler (infix, reified)
registerNotification(handler)Register a notification handler (infix, reified)
registerValidator(validator)Register a request validator (reified)
registerDynamic(klass, handler)Register a request handler without reified type (for DI frameworks)
scope { }Group registrations for readability
+handlerOperator shorthand for register / registerNotification inside scope
hasHandler(requestType)Returns true if a handler is registered for the given request type
registeredRequestTypes()Returns the set of all request types that have a registered handler

MediatorFactory

object MediatorFactory {
fun create(
registrars: List<MediatorRegistrar> = emptyList(),
pipelineBehaviors: List<PipelineBehavior> = emptyList(),
streamPipelineBehaviors: List<StreamPipelineBehavior> = emptyList(),
notificationPublisher: NotificationPublishStrategy = ParallelNotificationPublisher(),
verifyHandlers: Boolean = true,
missingNotificationHandler: NotificationHandler<Notification> = ThrowMissingNotificationHandler(),
missingRequestHandler: RequestHandler<Request<Any?>, Any?> = ThrowMissingRequestHandler(),
): Mediator
}
ParameterDefaultDescription
registrarsemptyList()Modules that contribute handlers to the registry
pipelineBehaviorsemptyList()Cross-cutting decorators; grouped by Stage then sorted by order within each group
streamPipelineBehaviorsemptyList()Cross-cutting decorators for StreamRequest dispatches; sorted by order
notificationPublisherParallelNotificationPublisher()Strategy for delivering notifications
verifyHandlerstrueWhen true, logs a warning for every request type with no handler after all registrars have run
missingNotificationHandlerThrowMissingNotificationHandler()What to do when a notification is published with no registered handlers
missingRequestHandlerThrowMissingRequestHandler()What to do when send() is called for an unregistered request type

MediatorRegistrar

Contributes handlers to the registry at startup.

interface MediatorRegistrar {
fun register(registry: HandlerRegistry)
}

Mediator interface

interface Mediator : Sender, IStreamRequest, Publisher
MethodDescription
send(request)Dispatch a Request; returns TResponse. Throws MissingHandlerException if no handler.
stream(request)Dispatch a StreamRequest; returns a cold Flow<T>. Throws MissingStreamHandlerException if no handler.
publish(notification)Broadcast a notification using the default NotificationPublisher.
publish(notification, publisher)Broadcast a notification using the supplied publisher, overriding the default for this call only.

Notification publishers · com.fajrbahr.mediatork.notification

ClassBehaviour
ParallelNotificationPublisherAll handlers run concurrently (default)
SequentialNotificationPublisherHandlers run one-by-one; stops on first error
ContinueOnExceptionNotificationPublisherAll handlers run; errors collected into AggregateException
FireAndForgetNotificationPublisherReturns immediately; handlers run in the background

Exceptions

ClassDescription
MediatorExceptionBase class for all MediatorK errors
MissingHandlerExceptionNo handler registered for the dispatched request type
MissingStreamHandlerExceptionNo stream handler registered for the dispatched StreamRequest type
MissingNotificationHandlerExceptionNo handlers registered for a published notification type
AggregateExceptionOne or more notification handlers failed (from ContinueOnException…)

Validator package (com.fajrbahr.mediatork.validator)

TypeDescription
RequestValidator<T>Validates a request and returns ValidationResult. Register via registry.registerValidator(validator).
ValidationResultSealed class: Valid or Invalid(errors: List<*>)
ValidationBehaviorPre-built PipelineBehavior (order -50) that runs registered validators before the handler
ValidationExceptionThrown when validation fails; errors: List<*> carries all failure messages (any type — String, sealed class, enum, etc.)
rules { }Collect-all DSL — all check/require calls run, errors accumulated
rulesFailFast { }Stop-on-first DSL — execution stops at the first failing check/require
throwIfInvalid()Extension on ValidationResult — throws ValidationException if the result is Invalid