KStateMachine is a Kotlin DSL library for creating state machines and statecharts.
Documentation | Sponsors | Quick start | Samples | Install | Contribution | License | Discussions
KStateMachine is a Kotlin DSL library for creating state machines and statecharts.
Integration features are:
State management features:
[!IMPORTANT] SEE FULL DOCUMENTATION HERE
I highly appreciate that you donate or become a sponsor to support the project. Use ❤️ github-sponsors button to see supported methods and push the ⭐ star-button if you like this project.
stateDiagram-v2
direction LR
[*] --> GreenState
GreenState --> YellowState: SwitchEvent
YellowState --> RedState: SwitchEvent
RedState --> [*]
object SwitchEvent : Event
sealed class States : DefaultState() {
object GreenState : States()
object YellowState : States()
object RedState : States(), FinalState // Machine finishes when enters final state
}
fun main() = runBlocking {
// Create state machine and configure its states in a setup block
val machine = createStateMachine(this) {
addInitialState(GreenState) {
// Add state listeners
onEntry { println("Enter green") }
onExit { println("Exit green") }
// Setup transition
transition<SwitchEvent> {
targetState = YellowState
// Add transition listener
onTriggered { println("Transition triggered") }
}
}
addState(YellowState) {
transition<SwitchEvent>(targetState = RedState)
}
addFinalState(RedState)
onFinished { println("Finished") }
}
// Now we can process events
machine.processEvent(SwitchEvent)
machine.processEvent(SwitchEvent)
}
Simple Android 2D shooter game sample
The library itself does not depend on Android.
Complex syntax sample shows many syntax variants and library possibilities, so it looks messy
KStateMachine is available on Maven Central
and JitPack
repositories.
See install section in the docs for details.
dependencies {
// multiplatform artifacts, where <Tag> is a library version.
implementation("io.github.nsk90:kstatemachine:<Tag>")
implementation("io.github.nsk90:kstatemachine-coroutines:<Tag>")
}
Run ./gradlew build
or build with Intellij IDEA
.
The library is in a active development phase. You are welcome to propose useful features and contribute to the project. See CONTRIBUTING file.
Licensed under permissive Boost Software License