kstatemachine icon indicating copy to clipboard operation
kstatemachine copied to clipboard

KStateMachine is a Kotlin DSL library for creating state machines and statecharts.

KStateMachine

Build and test with Gradle Quality Gate Status Maven Central Dependencies none codecov Android Arsenal

KStateMachine is a Kotlin DSL library for creating finite state machines (FSM) and hierarchical state machines (HSM).

Overview

Main features are:

The library is currently in a development phase. You are welcome to propose useful features.

Don't forget to push the ⭐ if you like this project.

SEE FULL DOCUMENTATION HERE

Quick start sample (finishing traffic light)

Traffic light diagram

sealed class Events {
    object NextEvent : Event
}

sealed class States {
    object GreenState : DefaultState()
    object YellowState : DefaultState()
    object RedState : DefaultFinalState() // Machine finishes when enters final state
}

fun main() {
    // Create state machine and configure its states in a setup block
    val machine = createStateMachine {
        addInitialState(GreenState) {
            // Add state listeners
            onEntry { println("Enter green") }
            onExit { println("Exit green") }

            // Setup transition
            transition<NextEvent> {
                targetState = YellowState
                // Add transition listener
                onTriggered { println("Transition triggered") }
            }
        }

        addState(YellowState) {
            transition<NextEvent>(targetState = RedState)
        }

        addFinalState(RedState)

        onFinished { println("Finished") }
    }

    // Now we can process events
    machine.processEvent(NextEvent)
    machine.processEvent(NextEvent)
}

Samples

  • Simple Android 2D shooter game sample

    The library itself does not depend on Android.

    Android sample app

  • PlantUML nested states export sample

  • Inherit transitions by grouping states sample

  • Minimal sealed classes sample

  • Minimal syntax sample

  • Guarded transition sample

  • Cross level transition sample

  • Typesafe transition sample

  • Complex syntax sample shows many syntax variants and library possibilities, so it looks messy

Install

KStateMachine is available on Maven Central and JitPack repositories.

Maven Central

Add the dependency:

dependencies {
    implementation 'io.github.nsk90:kstatemachine:<Tag>'
}

Where <Tag> is a library version.

JitPack

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        //  ...
        maven { url 'https://jitpack.io' }
    }
}

Add the dependency:

dependencies {
    implementation 'com.github.nsk90:kstatemachine:<Tag>'
}

Where <Tag> is a library version.

Build

Run ./gradlew build or build with Intellij IDEA.

To run tests from IDE download official Kotest plugin.

Licensed under the Boost Software License