Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Created March 29, 2014 18:24
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 JavadocMD/9859519 to your computer and use it in GitHub Desktop.
Save JavadocMD/9859519 to your computer and use it in GitHub Desktop.
package com.javadocmd
import akka.actor.Actor
import akka.actor.FSM
import akka.actor.Props
import akka.actor.ActorSystem
import akka.actor.LoggingFSM
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.collection._
// States
sealed trait State
case object Ready1 extends State
case object Ready2 extends State
// Messages
final case class Number(n: Int)
final object Done
// Data
sealed trait Data
case object Uninitialized extends Data
case class Normal(n: Int) extends Data
case object Fizzed extends Data
case object Buzzed extends Data
case object FizzBuzzed extends Data
class FizzBuzz extends Actor with LoggingFSM[State, Data] {
startWith(Ready1, Uninitialized)
when(Ready1)(readyTransitionsTo(Ready2))
when(Ready2)(readyTransitionsTo(Ready1))
def readyTransitionsTo(sisterState: com.javadocmd.State): StateFunction = {
case Event(Number(integer), _) => integer match {
case i: Int if (i % 15 == 0) => goto(sisterState) using(FizzBuzzed)
case i: Int if (i % 5 == 0) => goto(sisterState) using(Buzzed)
case i: Int if (i % 3 == 0) => goto(sisterState) using(Fizzed)
case i: Int => goto(sisterState) using(Normal(i))
}
case Event(Done, _) => stop()
}
onTransition {
case _ -> Ready1 | _ -> Ready2 =>
nextStateData match {
case Normal(i) => println(i.toString)
case Fizzed => println("Fizz")
case Buzzed => println("Buzz")
case FizzBuzzed => println("FizzBuzz")
case Uninitialized =>
}
}
initialize()
}
object FizzBuzzApp {
def main(args: Array[String]) {
val actors = ActorSystem()
val fb = actors.actorOf(Props(classOf[FizzBuzz]))
(1 to 30) foreach (fb ! Number(_))
fb ! Done
future {
blocking(Thread.sleep(1000L))
actors.shutdown()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment