Skip to content

Instantly share code, notes, and snippets.

@eyston
Created July 2, 2011 20:01
Show Gist options
  • Save eyston/1061591 to your computer and use it in GitHub Desktop.
Save eyston/1061591 to your computer and use it in GitHub Desktop.
Example of Akka Actor Become
import akka.actor.Actor
// defining messages -- Object = singleton, case class = DTO (sorta, generally)
object Born
case class Evolve(numberOfNeighbors: Int)
object Status
// receive is the method that handles incoming messages.
// alive: Receive and dead: Receive are defining alternative ways to respond to messages
// these will be switched on during runtime
class Cell extends Actor {
def alive: Receive = {
case Evolve(neighbors) => {
if(neighbors < 2) become(dead)
else if (neighbors > 3) become(dead)
}
case Status => println("alive!")
}
def dead: Receive = {
case Evolve(neighbors) => {
if(neighbors == 3) become(alive)
}
case Status => println("dead :(")
}
def receive = {
case Born => become(alive)
case Status => println("I am nothing...")
}
}
object Main extends App {
val cell = Actor.actorOf[Cell] // returns reference, very few public methods (id, start, stop, etc)
cell.start // starts responding to messages
// ! = send message ... so we are sending Status message to cell
cell ! Status // > I am nothing ...
cell ! Born
cell ! Status // > alive!
cell ! Evolve(4)
cell ! Status // > dead :(
cell ! Evolve(3)
cell ! Status // alive!
// async calls so being lazy and just adding thread sleep ~
Thread.sleep(250)
cell.stop
}
// the whole born thing kinda sucks as its an undefined state (neither alive nor dead).
// you'd want a factory to create alive or dead cells, although I think in most solutions
// you don't want a cell class at all :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment