Created
June 12, 2013 17:24
-
-
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 …
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
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