Skip to content

Instantly share code, notes, and snippets.

@tlockney
Created June 12, 2013 17: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 tlockney/5767338 to your computer and use it in GitHub Desktop.
Save tlockney/5767338 to your computer and use it in GitHub Desktop.
While immutable data structures are preferable in Scala, it's not always obvious how to utilize them inside of an Akka actor when you need the actor to be stateful. Thankfully, Akka provides some help here, by use of the become method, which is designed to update the behavior of an actor. Scala supports closures, so we can pass the new state in …
import akka.actor.Actor
// Following the common Akka pattern of defining the messaging
// protocol in the companion object
object SampleActor {
case object GetState
case class UpdateState(key: String, value: String)
}
class SampleActor extends Actor {
// This case class represents the actor's state
case class State(someData: Map[String, String])
// Initialize the actors behavior with an empty state
def receive = updated(State(Map.empty))
// This defines the behavior of the actor. Note that there could be
// multiple definitions like this, with the actor switching behaviors
// and not just state.
def updated(state: State): Receive = {
case UpdateState(k, v) =>
context.become(state.copy(state.someData ++ (k -> v)))
case GetState =>
sender ! state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment