Skip to content

Transformer

A transformer is a unit of business logic: it owns state, handles signals and effects, and serves queries and commands to other transformers. Build one with transformer { }; the result is a regular Transformer that any router accepts.

Building a Transformer

fun cartTransformer() = transformer(Cart) {
    val cart = state(Cart.state)                  // published on every change

    on<CartEffect.AddItem> { effect ->
        val product = Catalog.productById(effect.productId) ?: return@on   // query another transformer
        cart.update { it.add(product) }
    }
    on<CartSignal.ChangeQuantity> { signal -> cart.update { it.changeQuantity(signal.productId, signal.delta) } }

    answer(Cart.summary) { cart.value }                         // serve a query
    handle(Cart.clear) { cart.value = CartState() }             // serve a command

    onError { throwable -> log(throwable) }
}
Builder function Purpose
transformer(name) { } / transformer(contracts) { } Creates the transformer; with a Contracts object, others can target it with publish(effect, to = Cart)
state(handle) State published as handle, starting from its declared initial value; a StateFlow you assign or update
on<T> { } Handles a signal or effect of type T; several handlers for one type all run, in order
accepts<T>() Routes T here without a handler, for awaitSignal
answer(query) { } Serves a query; runs in the caller's coroutine, so read state only
handle(command) { } Serves a command; runs in this transformer's mailbox, in call order
onError { }, onCleared { } Called on a handler exception (processing continues) and when the router is cleared

Inside handlers you can emit(data), publish(effect), publish(effect, to = …), call handles (Cart.summary(), Cart.clear()), and wait for the next message with awaitSignal<T>(). See Handlers and Transformer Communication.

A Multi-Step Flow

The shop's checkout is one handler that reads top to bottom. It waits for each of the user's steps with awaitSignal, giving up its turn while it waits (samples/shop/shared/src/commonMain/kotlin/com/yigitozgumus/transmission/shop/checkout/CheckoutTransformer.kt):

fun checkoutTransformer(paymentGateway: PaymentGateway) = transformer(Checkout) {
    val state = state(Checkout.state)
    fun cancelled() { state.value = CheckoutState(message = "Checkout cancelled.") }

    accepts<CheckoutSignal.SubmitAddress>()
    accepts<CheckoutSignal.SubmitPayment>()
    accepts<CheckoutSignal.Cancel>()

    on<CheckoutSignal.Start> {
        val cart = Cart.summary()
        state.value = CheckoutState(step = CheckoutStep.Address, cart = cart)

        val address = awaitSignal<CheckoutSignal.SubmitAddress>(cancelOn = CheckoutSignal.Cancel::class)
            ?.address ?: return@on cancelled()
        state.update { it.copy(step = CheckoutStep.Payment, address = address) }

        while (true) {
            val payment = awaitSignal<CheckoutSignal.SubmitPayment>(cancelOn = CheckoutSignal.Cancel::class)
                ?.payment ?: return@on cancelled()
            val orderId = try {
                paymentGateway.charge(payment, cart.totalCents)
            } catch (declined: PaymentDeclinedException) {
                state.update { it.copy(step = CheckoutStep.Payment, message = declined.message) }
                continue
            }
            Cart.clear()
            publish(CheckoutEffect.OrderPlaced(orderId, cart.totalCents))
            state.update { it.copy(step = CheckoutStep.Confirmed(orderId)) }
            return@on
        }
    }
}

Concurrency Guarantees

Each transformer processes its signals, effects and commands one at a time, in arrival order, through a single mailbox. Handlers of one transformer never run concurrently, so plain var state inside a transformer is safe.

  • Messages from one sender to one transformer arrive in the order they were sent.
  • router.process(...) calls are routed in caller order; calls made before the router finishes initializing are delivered once it is ready.
  • Data from one transformer reaches observers in the order it was sent; initial data holder values come first.
  • Different transformers run concurrently. There is no global order across transformers.
  • emit, publish and commands (Cart.clear()) never suspend. Queries and state reads (Cart.summary(), Cart.state()) wait for their answer while keeping the turn.
  • awaitSignal gives up the turn while waiting, so other messages can run; the next matching message goes to the waiting handler, which continues right after it.
  • answer blocks run in the caller's coroutine, outside the owner's mailbox, and should only read state. Cancelling the caller cancels them.
  • Queries are answered directly, without messaging: state reads use the owner's storage, and commands go to the owner's mailbox in call order.

Options

transformer(...) takes a dispatcher before the block (default Dispatchers.Default): where its handlers run. The shop passes one in so tests can use a StandardTestDispatcher and run processing in virtual time:

fun catalogTransformer(repository: ProductRepository, dispatcher: CoroutineDispatcher = Dispatchers.Default) =
    transformer(Catalog, dispatcher) { … }

Buffer sizes are set on the router, with setCapacity(...); see Router.

Dependencies

A transformer is a function call, so pass dependencies as parameters, as the shop does with its repository and payment gateway. With dependency injection, create transformers in the module that creates the ViewModel:

val viewModelModule = module {
    viewModel { CatalogViewModel(catalogTransformer(get())) }
    viewModel { CheckoutViewModel(checkoutTransformer(get())) }
}

Create a new transformer for each router. A transformer belongs to the router that loads it and is cleared with it.

Lifecycle

  • Start: when a router loads the transformer, its initial state is published, then messages start arriving.
  • Clear: when the router's scope ends, the router clears its transformers. onCleared { } runs, waiting handlers are cancelled, and nothing more is processed.
  • Errors: onError { } sees every exception from a handler or command; processing continues with the next message.

Guidelines

  • One feature per transformer: a transformer owns one Contracts object. Split a transformer that serves unrelated features.
  • Immutable state: change state with copy through state.update { }.
  • Contracts between features: reach other features only through their handles and effects, never through references.
  • Logic in plain functions: keep handlers short and test the domain rules, like CartState.changeQuantity, without a router.

Classic API (Deprecated)

Classic transformers are Transformer subclasses configured with configure { }, or the classic transformer(identity) { } with a configuration scope. That style is deprecated; it keeps working in 2.x, and builder and classic transformers can share a router while you migrate.

Classic (deprecated) Builder
class CartTransformer : Transformer(identity) fun cartTransformer() = transformer(Cart) { }
configure { onSignal<T> { } } on<T> { }
dataHolder(initial, contract) state(handle), with the initial value on the handle
computation(contract) { }, execution(contract) { } answer(query) { }, handle(command) { }
override fun onError(...), onCleared() onError { }, onCleared { }
pauseOn / validate awaitSignal<T>()

The old reference is kept in Classic API: Transformer.