Skip to content

Instantly share code, notes, and snippets.

@motorro
Last active July 31, 2022 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motorro/88c3b397a906de752abb7394256ed713 to your computer and use it in GitHub Desktop.
Save motorro/88c3b397a906de752abb7394256ed713 to your computer and use it in GitHub Desktop.
State machine implementation
/**
* Common state machine
* @param G UI gesture
* @param U UI state
*/
interface CommonStateMachine<G: Any, U: Any> : MachineInput<G>, MachineOutput<G, U> {
/**
* Base state-machine implementation
* @param init Initial state producer
*/
abstract class Base<G: Any, U: Any>(
private val init: () -> CommonMachineState<G, U>
) : CommonStateMachine<G, U> {
/**
* Active machine state
*/
protected lateinit var activeState: CommonMachineState<G, U>
/**
* Sets active machine state
*/
final override fun setMachineState(machineState: CommonMachineState<G, U>) {
clear()
activeState = machineState
startMachineState()
}
/**
* Starts machine
*/
protected fun start() {
activeState = init()
startMachineState()
started = true
}
/**
* Updates state with UI gesture
* @param gesture UI gesture to proceed
*/
final override fun process(gesture: G) {
activeState.process(gesture)
}
/**
* Cleans-up state-machine
*/
final override fun clear() {
activeState.clear()
}
/**
* Starts machine state
*/
private fun startMachineState() {
activeState.start(this)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment