项目作者: ToxicBakery

项目描述 :
Kotlin Finite State Machine
高级语言: Kotlin
项目地址: git://github.com/ToxicBakery/kfin-state-machine.git
创建时间: 2018-02-18T20:03:25Z
项目社区:https://github.com/ToxicBakery/kfin-state-machine

开源协议:Apache License 2.0

下载


Kotlin Finite State Machine

CircleCI codecov Maven Central Maven Central
Kotlin library for creating finite state machines.

It is an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can
change from one state to another in response to some external inputs; the change from one state to another is called a
transition. An FSM is defined by a list of its states, its initial state, and the conditions for each transition.
Wikipedia - Finite-state machine

Sample Usage

  1. sealed class Energy {
  2. object Kinetic : Energy()
  3. object Potential : Energy()
  4. }
  5. sealed class EnergyTransition {
  6. object Store : EnergyTransition()
  7. object Release : EnergyTransition()
  8. }
  9. val stateMachine = StateMachine(
  10. Potential,
  11. Potential onEvent Release::class resultsIn Kinetic,
  12. Kinetic onEvent Store::class resultsIn Potential
  13. )
  14. // Get the current state, will initially return `Potential`
  15. machine.state
  16. // Move the machine to `Kinetic`
  17. machine.transition(Release)

Samples

Samples intend to show various ways the library might be used.

  • Dungeon - MUD style application allowing a player to explore a randomly generated dungeon
  • Stopwatch - Simple stopwatch that counts from zero at one second intervals until stopped.

Install

Kfin is now a Kotlin Multiplatform project supporting js, jvm, and jvmRx platforms.

kfin - includes base state machine implementation

  1. compile "com.ToxicBakery.kfinstatemachine:kfin-<platform>:4.+"

Graph - includes directed graph implementation which can be used to create large state machines more easily

  1. compile "com.ToxicBakery.kfinstatemachine:graph-<platform>:4.+"

Build

The library depends on gradle for compilation and requires JDK 8 or higher.

./gradlew build

Considerations

This library originally took a classical approach using a directed graph for state and callbacks for listening to state
and transition changes. Thanks to a talk given by Ray Ryan from Square, I created an implementation generally following
their state machine API and reworked my examples to fit. The exact slide can be
found here and the talk in its whole is worth the watch.