RepositoryKotlin
KStateMachine

KStateMachine/kstatemachine

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

517stars
30forks
0issues
3views

Featured achievements

The project's latest awards

1
TINIX TRENDING·Topic: nested-states

#1 Repository of the month

1
TINIX TRENDING·Topic: transitions

#1 Repository of the month

1
TINIX TRENDING·Topic: hsm

#1 Repository of the month

KStateMachine

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


Build codecov Maven Central JitPack Multiplatform JetBrains Marketplace

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


📖 Documentation  |  📚 KDoc  |  🔌 IntelliJ Plugin  |  🚀 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
Fork & JoinSynchronize concurrent orthogonal regions (UML fork/join pseudo-states)
Undo transitionsNavigate back like a stack-based FSM

Tooling

FeatureDescription
IntelliJ PluginVisualise, navigate, and export state machines directly from your IDE — no runtime needed
ExportGenerate PlantUML or Mermaid diagrams from your machine definition
Persist & restoreTwo strategies: event recording (full replay) or state snapshot (captureSavedStateConfig) — both serialisable via kotlinx.serialization
Testing helpersstartFrom(state) bypasses normal init, enabling focused unit tests
Library comparisonSide-by-side feature matrix vs FlowRedux, Tinder StateMachine, and Spring State Machine

🔌 IntelliJ IDEA Plugin

KStateMachine Visual is an IntelliJ IDEA plugin that visualizes and navigates your state machines straight from Kotlin source — no runtime required.

  • Tree view with specialized icons for every state type (initial, final, choice, history, data, parallel)
  • Bidirectional navigation between the editor and the tree view
  • Live PlantUML diagram — rendered inline with debounced real-time updates as you type (no Graphviz needed)
  • Export as SVG or raw PlantUML source
  • Static analysis — resolves the full DSL tree including states inside conditional branches that runtime export misses

Install: Settings → Plugins → Marketplace → search KStateMachine Visual

See the plugin documentation page for the full feature reference and manual install instructions.


📄 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+ runnable 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.

Similar Projects

Discover other similar projects and AI models.

RepositoryC#
Real-Serious-Games/Fluent-State-Machine

Fluent API for creating state machines in C#

281
Aug 12, 2019
RepositoryPython
fgmacedo/python-statemachine

Expressive statecharts and FSMs for modern Python.

1.3k
Oct 23, 2026
RepositoryRust
mdeloof/statig

Hierarchical state machines for designing event-driven systems

814
Nov 29, 2025
RepositoryTypeScript
StoneCypher/jssm

Fast, easy Javascript finite state machines with visualizations; enjoy a one liner FSM instead of pages. MIT; Typescripted; 100% test coverage. Implements the FSL language.

373
Nov 14, 2026
RepositoryC++
igor-krechetov/hsmcpp

C++ based Hierarchical / Finite State Machine library oriented for embedded and RTOS systems.

130
Nov 17, 2026
RepositoryTypeScript
statelyai/xstate

State machines, statecharts, and actors for complex logic

30.6k
Nov 30, 2026
RepositoryPython
apache/burr

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

2.6k
Dec 1, 2026
RepositoryPython
viewflow/django-fsm

Django friendly finite state machine support

2.3k
Nov 13, 2026
RepositoryTypeScript
ifandelse/machina.js

ts ex machina - finite state machines in TypeScript

2.0k
Nov 14, 2026