Type-safe finite state machine with DSL, transition guards, and side effects
implementation com.philiprehberger:state-machineType-safe finite state machine with DSL, transition guards, and side effects.
implementation("com.philiprehberger:state-machine:0.2.0")
<dependency>
<groupId>com.philiprehberger</groupId>
<artifactId>state-machine</artifactId>
<version>0.2.0</version>
</dependency>
import com.philiprehberger.statemachine.*
sealed class State { object Idle : State(); object Running : State() }
sealed class Event { object Start : Event(); object Stop : Event() }
val sm = stateMachine<State, Event>(State.Idle) {
state<State.Idle> { on<Event.Start> { transitionTo(State.Running) } }
state<State.Running> { on<Event.Stop> { transitionTo(State.Idle) } }
}
sm.send(Event.Start) // currentState = Running
sm.canSend(Event.Stop) // true
sm.send(Event.Start)
sm.send(Event.Stop)
sm.history().forEach { t ->
println("${t.from} --[${t.event}]--> ${t.to}")
}
val events = sm.availableEvents()
// Returns the set of event classes valid for the current state
sm.reset() // Returns to initial state, clears history
| Function / Class | Description |
|---|---|
stateMachine(initial) { } | DSL to define a state machine |
state<S> { on<E> { } } | Define transitions for a state |
transitionTo(state) | Set the target state |
guard { s, e -> Boolean } | Conditional transition |
sideEffect { from, event, to -> } | Execute on transition |
StateMachine.send(event) | Trigger a state transition |
StateMachine.canSend(event) | Check if transition is valid |
StateMachine.currentState | Current state |
StateMachine.history() | Get list of all transitions made |
StateMachine.availableEvents() | Get valid events for current state |
StateMachine.reset() | Reset to initial state, clear history |
Transition<S, E> | Records from, event, to, and timestamp |
./gradlew test
./gradlew build
If you find this project useful: