Skip to content

Handlers

Handlers decide what a transformer does with each message. In transformer { }, on<T> handles a signal or an effect of type T; handlers of one transformer run one at a time, in arrival order.

Handling Messages

fun cartTransformer() = transformer(Cart) {
    val cart = state(Cart.state)

    on<CartEffect.AddItem> { effect ->                 // an effect from another transformer or router
        val product = Catalog.productById(effect.productId) ?: return@on
        cart.update { it.add(product) }
    }
    on<CartSignal.RemovePromo> {                        // a signal from the UI
        cart.update { it.copy(promo = null, promoError = null) }
    }
}
  • Matching is by exact type: a handler for a parent type does not receive subtypes.
  • Several on<T> for the same type all run, in registration order.
  • A handler that throws is reported to onError; the transformer keeps processing.
  • Handlers can't change after the router starts; declare them all in the builder.

Waiting for the Next Message

awaitSignal<T>() suspends a handler until the next T reaches the transformer, and returns it. While it waits the handler gives up its turn, so the transformer keeps processing other messages; it continues right after the message that released it. Declare awaited types with accepts<T>() so the router delivers them:

accepts<SubmitAddress>()
accepts<Cancel>()

on<Checkout.Start> {
    val address = awaitSignal<SubmitAddress>(cancelOn = Cancel::class)?.address ?: return@on cancelled()
    val confirmed = awaitSignal<Confirm>(timeout = 5.minutes) ?: return@on timedOut()
}
Form Returns
awaitSignal<T>() The next T
awaitSignal<T>(cancelOn = C::class) The next T, or null if a C arrives first
awaitSignal<T>(timeout = d) The next T, or null after d

Because the mailbox is FIFO, sending Start and then SubmitAddress back to back always works: the waiting handler registers before the next message is looked at. Waiting on a type that is never routed here fails immediately with a message naming the fix.

What a Handler Can Do

Call Effect
emit(data) Sends data to observers
publish(effect) Broadcasts an effect to every transformer that handles it, and to other global routers
publish(effect, to = Cart) Sends an effect only to the transformer that owns Cart
Cart.state() Reads another transformer's current state
Cart.summary(), Catalog.productById(id) Asks a query and waits for the answer
Cart.clear() Triggers a command in its owner and returns at once
awaitSignal<T>() Waits for the next T, as below

emit, publish and commands never suspend the handler. Queries and state reads wait for their answer while keeping the transformer's turn. See Transformer Communication.

Errors

A handler that throws is reported to the transformer's onError, and the next message is handled as usual. The lab screen in the sample shows this: after any number of failures, the transformer keeps answering.

fun resilientTransformer() = transformer("resilience") {
    var errorsCaught = 0
    on<Explode> { error("Boom") }
    on<Ping> { emit(ResilienceResult(errorsCaught)) }
    onError { errorsCaught++ }
}

Catch inside the handler when the failure is part of the feature, such as a declined card, and update state to show it:

val orderId = try {
    paymentGateway.charge(payment, cart.totalCents)
} catch (declined: PaymentDeclinedException) {
    state.update { it.copy(step = CheckoutStep.Payment, message = declined.message) }
    continue
}

Patterns

  • One handler per message: keep each on<T> short, and move domain logic into plain functions such as CartState.add(product), which you can test without a router.
  • Immutable state: update state with copy, as in cart.update { it.copy(promo = null) }, so observers never see a half-changed value.
  • Multi-step flows: write the steps in order in one handler with awaitSignal, as the shop's checkout does, instead of a state machine spread over several handlers. See Transformer.
  • Reacting to other features: handle their effects with on<T>. To hear only what concerns it, a transformer can be the target of publish(effect, to = …).

Classic API (Deprecated)

Classic transformers register handlers inside configure { }. That API is deprecated, and checkpoints will be removed in 3.0.

Classic (deprecated) Builder
onSignal<T> { }, onEffect<T> { } on<T> { }
send(data) emit(data)
send(effect, identity) publish(effect, to = contracts)
compute(contract), getData(contract), execute(contract) Cart.summary(), Cart.state(), Cart.clear()
pauseOn(checkpoint) / validate(checkpoint, value) awaitSignal<T>()

The old reference is kept in Classic API: Handlers.