Finite State Machine in Akka
Dmytro Bischak 2017
Mathematical Model of Computation
State(S) x Event(E) -> Actions (A), State(S')
Blackbox
Event #1
Event #2
Event #3
State A
Behaviour A
State B
Behaviour B
State C
Behaviour C
States, Events, Data
Turnstile
How It Works
State
Only one State at time
State is Behaviour
Getting state is not an Action
State Example
sealed trait State
case object Locked extends State
case object UnLocked extends State
when(Locked) {
case Event(Push, _) =>
println("<Locked!>")
stay()
}
Event
val turnstile = system.actorOf(Props[Turnstile])
turnstile ! Coin
Just a regular message to FSM Actor
Data
FSM doesn’t have data fields
State encapsulation
when(States.UnLocked) {
case Event(Coin(money), StateData(total)) =>
println(s"<Even more Coins, money: $money, old total: $total>")
stay() using StateData(money + total)
}
Timeout
StateTimeout Event
Only when no other Events occur!
when(Locked) {
case Event(Coin, _) =>
goto(UnLocked) forMax TIMEOUT
}
when(States.UnLocked) {
case Event(StateTimeout, _) =>
goto(Locked)
}
State Transition
onTransition callback on state changes
Occur only with goto(StateA), not stay()
onTransition {
case UnLocked -> Locked =>
println("<Transition UnLocked -> Locked>")
}
Examples
https://github.com/bischak/akka-fsm
Conclusions
High level DSL
Easy to describe discrete models
Omitting shared state issues
Thank You
Questions?

Finite State Machine in Akka