commonMain.ru.kontur.mobile.visualfsm.Action.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of visualfsm-core Show documentation
Show all versions of visualfsm-core Show documentation
VisualFSM - Kotlin Multiplatform library for FSM with visualization and analysis tools
package ru.kontur.mobile.visualfsm
/**
* Is an input object for the State machine.
* The [action][Action] chooses [transition][Transition] and performs it
*/
abstract class Action {
/**
* Returns every [Transition] declared inside [Action]
*
* @return every [Transition] declared inside [Action]
*/
abstract fun getTransitions(): List>
/**
* Selects and starts a [transition][Transition].
* Calls [transition callbacks][TransitionCallbacks] methods.
*
* @param oldState current [state][State]
* @param callbacks [transition callbacks][TransitionCallbacks]
* @return [new state][State]
*/
fun run(oldState: STATE, callbacks: TransitionCallbacks?): STATE {
callbacks?.onActionLaunched(this, oldState)
val availableTransitions = getAvailableTransitions(oldState)
if (availableTransitions.size > 1) {
callbacks?.onMultipleTransitionError(this, oldState)
}
val selectedTransition = availableTransitions.firstOrNull()
if (selectedTransition == null) {
callbacks?.onNoTransitionError(this, oldState)
return oldState
}
callbacks?.onTransitionSelected(this, selectedTransition, oldState)
val newState = selectedTransition.transform(oldState)
callbacks?.onNewStateReduced(this, selectedTransition, oldState, newState)
return newState
}
@Suppress("UNCHECKED_CAST")
private fun getAvailableTransitions(oldState: STATE): List> =
(getTransitions() as List>).filter { isCorrectTransition(it, oldState) }
private fun isCorrectTransition(
transition: Transition,
oldState: STATE
): Boolean =
(transition.fromState == oldState::class) && transition.predicate(oldState)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy