Last active
December 30, 2015 15:59
-
-
Save nicerobot/7851299 to your computer and use it in GitHub Desktop.
Akka Actor state (i.e. become/unbecome)
This file contains hidden or 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
| name := "state" | |
| scalaVersion := "2.10.3" | |
| scalacOptions ++= Seq("-unchecked", "-deprecation") | |
| libraryDependencies ++= Seq( | |
| "com.typesafe.akka" %% "akka-actor" % "2.2.3", | |
| "com.ning" % "async-http-client" % "1.7.19", | |
| "ch.qos.logback" % "logback-classic" % "1.0.7") |
This file contains hidden or 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
| #!/bin/bash | |
| # curl -ks https://gist.github.com/nicerobot/7851299/raw/run.sh | bash - | |
| [ -f State.scala ] || { | |
| [ -d 7851299 ] || { | |
| git clone https://gist.github.com/7851299.git | |
| } | |
| cd 7851299 | |
| } | |
| sbt -Dakka.loglevel=DEBUG -Dakka.actor.debug.receive=true 'run-main akka.Main test.State' |
This file contains hidden or 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
| package test | |
| import akka.actor.Actor | |
| import akka.actor.Props | |
| import akka.actor.ReceiveTimeout | |
| import scala.concurrent.duration._ | |
| import akka.actor.ActorLogging | |
| import akka.event.LoggingReceive | |
| case class Next() | |
| case class Status() | |
| class State extends Actor with ActorLogging { | |
| context setReceiveTimeout 3.seconds | |
| self ! Status | |
| // Change and check the state 4 times. | |
| // Initial->Alive, Alive->Dead, Dead->Alive, Alive->Dead | |
| for (i <- 1 to 4) { | |
| self ! Next | |
| self ! Status | |
| } | |
| def next(name: String)(nextState: => Receive, doTimeout: => Unit): Receive = { | |
| LoggingReceive { | |
| case Next => context become nextState | |
| case Status => println(s"${name}!") | |
| case ReceiveTimeout => { | |
| println(s"${name} timeout") | |
| doTimeout | |
| } | |
| } | |
| } | |
| def orUndo = context unbecome | |
| def orStop = context stop self | |
| def fromAliveTo = next("alive") _ | |
| def fromDeadTo = next("dead") _ | |
| def fromInitialTo = next("initial") _ | |
| def alive: Receive = fromAliveTo(dead, orUndo) | |
| def dead: Receive = fromDeadTo(alive, orUndo) | |
| def receive: Receive = fromInitialTo(alive, orStop) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment