Created
January 16, 2018 10:36
-
-
Save mahesh2492/62dd09dbb0300a7817600bd2fc920d5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed trait State | |
case object Waiting extends State | |
case object Active extends State | |
case class Msg(a: Int) | |
case object Flush | |
case class StateData(queue: immutable.Queue[Msg]) | |
class SizeBasedThrottler extends FSM[State, StateData] { | |
startWith(Waiting, StateData(Queue.empty)) | |
onTransition { | |
case Waiting -> Active => | |
nextStateData match { | |
case StateData(queue) => | |
for(x <- queue) yield println(s"$curTime processing ${x.a} ") | |
Thread.sleep(2000L) // used just to depict as real time problem take time to process request | |
} | |
} | |
when(Active) { | |
case Event(msg: Msg, _) => | |
println(s"$curTime at Active $msg" ) | |
goto(Waiting) using StateData(Queue(msg))//StateData.single(msg) | |
} | |
when(Waiting, stateTimeout = 2 seconds){ | |
case Event(msg: Msg, StateData(oldQueue)) => | |
val newQueue = oldQueue :+ msg | |
println(s"$curTime at Idle $newQueue") | |
stay() using StateData(newQueue) | |
case Event(Flush, StateData(queue)) => goto(Active) using StateData(queue) | |
case Event(StateTimeout, StateData(queue)) => goto(Active) using StateData(queue) | |
} | |
initialize() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment