StateMachineBuilder

DSL builder for creating state machines with a fluent API.

This builder provides a declarative way to define state machines similar to the coroutine-based guide but adapted for zero dependencies. It supports event handling, state transitions, guards, and side effects.

Parameters

S

The type of states in the state machine

E

The type of events in the state machine

Constructors

Link copied to clipboard
constructor()

Properties

Link copied to clipboard

The initial state of the state machine. Must be set before building.

Link copied to clipboard

Starts the initial state configuration with "starting at State" syntax.

Link copied to clipboard

Optional validator for state validation.

Link copied to clipboard

Starts observer configuration with "watching" keyword.

Functions

Link copied to clipboard
inline fun <S : Any, E : StateEvent> StateMachineBuilder<S, E>.during(state: S, configuration: StateConversationalScope<S, E>.() -> Unit)

Configures a state with conversational syntax: "during State { ... }"

Link copied to clipboard
infix fun <S, E : StateEvent> StateMachineBuilder<S, E>.initially(state: S)

Alternative syntax for setting initial state: "initially State"

Link copied to clipboard
fun observe(observer: StateObserver<S>)

Adds an observer to the state machine.

fun observe(observer: (oldState: S, newState: S) -> Unit)

Adds an observer using a lambda.

Link copied to clipboard
inline fun <T : E> onAny(handler: StateEventHandler<S, T>)

Adds a global event handler using reified generics.

fun <T : E> onAny(eventClass: KClass<T>, handler: StateEventHandler<S, T>)

Adds a global event handler that applies to all states.

Link copied to clipboard
fun <S, E : StateEvent> StateMachineBuilder<S, E>.onEveryTransition(effect: (oldState: S, newState: S) -> Unit)

Adds a global side effect that runs on every transition.

Link copied to clipboard
fun sideEffect(effect: (oldState: S, newState: S) -> Unit)

Adds a side effect that runs on every state transition.

Link copied to clipboard
inline fun <T : Any> state(noinline configuration: StateConfiguration<S, E>.() -> Unit)

Configures a specific state using reified generics.

fun <T : Any> state(stateClass: KClass<T>, configuration: StateConfiguration<S, E>.() -> Unit)

Configures a specific state in the state machine.

Link copied to clipboard
infix fun <S, E : StateEvent> StateMachineBuilder<S, E>.tracking(with: String): ((S, S) -> Unit) -> Unit

Adds an observer using "tracking with" syntax.

Link copied to clipboard

Sets the state validator directly.

Link copied to clipboard

Sets the state validator with conversational syntax.