README.md

May 30, 2026 Β· View on GitHub

KStateMachine

A powerful Kotlin Multiplatform state machine library with clean DSL syntax
and first-class Kotlin Coroutines support


Build codecov Maven Central JitPack Multiplatform

Open Collective Mentioned in Awesome Kotlin Android Arsenal Slack Share on X Share on Reddit


πŸ“– Documentation Β |Β  πŸ“š KDoc Β |Β  πŸš€ Quick Start Β |Β  πŸ§ͺ Samples Β |Β  πŸ’Ύ Install Β |Β  πŸ’¬ Discussions Β |Β  ❀️ Sponsors


What is KStateMachine?

KStateMachine lets you model complex application logic as a finite state machine or statechart using an expressive Kotlin DSL. It runs on every Kotlin Multiplatform target, integrates seamlessly with Kotlin Coroutines, and has zero mandatory dependencies.


πŸš€ Quick Start

Animated traffic light

Animated UML statechart β€” traffic light state machine
// Events
object SwitchEvent : Event

// States
sealed class States : DefaultState() {
    object RedState : States()
    object YellowState : States()
    object GreenState : States(), FinalState  // machine stops here
}

fun main() = runBlocking {
    val machine = createStateMachine(scope = this) {
        addInitialState(RedState) {
            onEntry { println("πŸ”΄ Red β€” stop!") }
            onExit { println("   leaving red") }

            transition<SwitchEvent> {
                targetState = YellowState
                onTriggered { println("   β†’ switching…") }
            }
        }

        addState(YellowState) {
            onEntry { println("🟑 Yellow β€” get ready") }
            transition<SwitchEvent>(targetState = GreenState)
        }

        addFinalState(GreenState) {
            onEntry { println("🟒 Green β€” go!") }
        }

        onFinished { println("βœ… Done") }
    }

    machine.processEvent(SwitchEvent) // Red β†’ Yellow
    machine.processEvent(SwitchEvent) // Yellow β†’ Green (finished)
}

Output

πŸ”΄ Red β€” stop!
   β†’ switching…
   leaving red
🟑 Yellow β€” get ready
🟒 Green β€” go!
βœ… Done

✨ Key Features

Integration

FeatureDescription
Kotlin DSLDeclarative, readable structure; plain API also available
Kotlin CoroutinesSuspending functions in listeners and guards; fully optional
Kotlin MultiplatformJVM, Android, iOS, JS, Wasm, Native
Zero dependenciesCore artifact depends only on the Kotlin stdlib

State management

FeatureDescription
Event-basedTransitions fire in response to events
Reactive listenersObserve machines, states, state groups, and transitions
Guarded & conditional transitionsDynamic target state computed at runtime
Nested statesFull statechart hierarchy with cross-level transitions
Composed state machinesEmbed one machine as a child state of another
Pseudo statesHistory, redirect, and other behavioural helpers
Typesafe transitionsCarry typed data from event to target state
Parallel statesRun orthogonal regions simultaneously
Undo transitionsNavigate back like a stack-based FSM

Tooling

FeatureDescription
ExportGenerate PlantUML or Mermaid diagrams from your machine definition
Persist & restoreRecord processed events and replay them to restore state; kotlinx.serialization built in
Testing helpersstartFrom(state) bypasses normal init, enabling focused unit tests

πŸ“„ Documentation

Important

Full documentation lives at kstatemachine.github.io/kstatemachine
KDoc for every class: kstatemachine.github.io/kstatemachine/kdoc


❀️ Sponsors

If KStateMachine saves you time, please consider supporting the project:

  • ⭐ Star this repo β€” it helps others discover it
  • ❀️ GitHub Sponsors β€” one-time or recurring donations
  • πŸ’› Open Collective β€” transparent team funding

πŸ§ͺ Samples

Full app samples and 20+ focused code samples are listed on the Samples page in the documentation.

Android sample app


✍️ Publications


πŸ’Ύ Install

KStateMachine is published to Maven Central and JitPack.

dependencies {
    // Core (zero dependencies)
    implementation("io.github.nsk90:kstatemachine:<Tag>")

    // + Kotlin Coroutines integration (optional)
    implementation("io.github.nsk90:kstatemachine-coroutines:<Tag>")

    // + kotlinx.serialization for state persistence (optional)
    implementation("io.github.nsk90:kstatemachine-serialization:<Tag>")
}

Replace <Tag> with the current version shown in the Maven Central badge above.
See the full install guide for Gradle Kotlin DSL, Groovy DSL, and JitPack variants.


πŸ—οΈ Build

./gradlew build          # build all modules
./gradlew :tests:jvmTest # run all tests (JVM target)

Or open in IntelliJ IDEA and run from there.


🀝 Contribution

The library is in stable phase β€” but feature proposals and pull requests are welcome!
Please read CONTRIBUTING.md before submitting.


πŸ™‹ Support

ChannelBest for
Slack #kstatemachineQuestions & discussions
GitHub DiscussionsQuestions & longer discussions
GitHub IssuesBug reports & feature requests

When asking on other platforms, include a link to this repo or use the #kstatemachine tag.


πŸ—ΊοΈ Roadmap

  • IntelliJ IDEA plugin β€” state machine visualization and editing

πŸ… Thanks to supporters

Stargazers Forkers


πŸ–‹οΈ License

Licensed under the permissive Boost Software License.