Skip to content

Contracts

A Contracts object lists what a feature offers to the rest of the app: its state, queries and commands. Each handle is a delegated property named after the object and the property, so errors and logs read Cart.summary.

Declaring Contracts

object Catalog : Contracts() {
    val state by state(CatalogState())
    val productById by queryWith<String, Product?>(cached = true)
}

object Cart : Contracts() {
    val state by state(CartState())
    val summary by query<CartState>()
    val clear by command()
}
Declaration Served with Called with
state(initial) state(handle) Cart.state() in a handler; router.state(handle) in UI code
query<R>(cached = false) answer(query) { } Cart.summary()
queryWith<A, R>(cached = false) answer(query) { args -> } Catalog.productById(id)
command() handle(command) { } Cart.clear()
commandWith<A>() handle(command) { args -> } Orders.cancel(orderId)

Contracts(name) takes an optional feature name; it defaults to the object's name and prefixes every handle name.

Serving a Feature

transformer(Cart) { } builds the transformer that owns Cart. It serves each handle in the builder (samples/shop/.../cart/CartTransformer.kt):

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

    on<CartEffect.AddItem> { effect ->
        val product = Catalog.productById(effect.productId) ?: return@on   // a query served in another router
        cart.update { it.add(product) }
    }

    answer(Cart.summary) { cart.value }
    handle(Cart.clear) { cart.value = CartState() }
}

The same object also addresses the transformer: other transformers send it a targeted effect with publish(effect, to = Cart).

State

state(initial) declares data the feature publishes and the value it starts from. The owner creates it with state(handle), which starts from that value (pass a second argument to start elsewhere); see State.

  • In a handler of another transformer, Cart.state() returns the owner's current value.
  • In UI code, router.state(Cart.state) is a StateFlow that follows it.

Queries

A query is a value other transformers ask for. Its answer block runs in the caller's coroutine, outside the owner's mailbox, so it should only read state:

object Catalog : Contracts() {
    val productById by queryWith<String, Product?>(cached = true)
}

fun catalogTransformer(repository: ProductRepository) = transformer(Catalog) {
    answer(Catalog.productById) { id -> repository.product(id) }
}

// in any transformer of this router, or of another router that called global():
val product = Catalog.productById("espresso")
  • Caching: with cached = true, the first answer is kept, per argument for queryWith. Pass invalidate = true to recompute: Catalog.productById(id, invalidate = true).
  • Nullable results: declare the type as nullable (Product?) when a query may have no answer.
  • Unserved queries: a query nobody serves throws ContractNotFoundException naming the handle, such as Catalog.productById.

Commands

A command is an operation that runs in its owner. Calling it returns immediately; the owner runs it in its mailbox, in call order, serialized with its handlers, so it may change state:

object Orders : Contracts() {
    val state by state(OrdersState())
    val cancel by commandWith<String>()
}

fun ordersTransformer() = transformer(Orders) {
    val orders = state(Orders.state)
    handle(Orders.cancel) { orderId -> orders.update { it.cancel(orderId) } }
}

// elsewhere:
Orders.cancel(orderId)

A command that throws is reported to its owner's onError, not to the caller.

Resolution

Queries, state reads and commands resolve in the caller's router first, then in other routers that called global(). Routers are isolated by default, so a feature in a router that hasn't called global() can't be reached from outside it.

Organizing Contracts

  • One object per feature: Cart, Catalog and Checkout each list only what that feature offers. The object name prefixes every handle, so errors and logs say which feature failed.
  • Messages beside contracts: keep a feature's signals, effects and state classes in the same file as its Contracts object, as the shop's CartContracts.kt does.
  • Specific argument types: prefer queryWith<SearchParams, SearchResult>() over a Map<String, Any> argument.
  • Cache expensive, stable answers: use cached = true for lookups like productById whose answer doesn't change.

Testing

In the test DSL, fake(...) stands in for whatever serves a handle; see Testing:

fake(Cart.summary) { cart }
val clearCart = fake(Cart.clear)

Classic API (Deprecated)

The classic Contract factories are deprecated; checkpoints will be removed in 3.0. Each builder handle wraps a classic contract, exposed as handle.contract, so classic and builder transformers can work together while you migrate.

Classic (deprecated) Builder
Contract.identity() transformer(name) { } or transformer(contracts) { }
Contract.dataHolder<T>() val state by state(initial)
Contract.computation<R>(useCache) val q by query<R>(cached)
Contract.computationWithArgs<A, R>() val q by queryWith<A, R>()
Contract.execution() / executionWithArgs<A>() val c by command() / commandWith<A>()
Contract.checkpoint() / checkpointWithArgs<A>() awaitSignal<T>()

The old reference is kept in Classic API: Contracts.