In some situations, we want our actor to change its behavior based on its state. This means that there are cases where an actor receives a message, and if its state changes or transitions, it changes the way further messages should be handled.
Thus, using become/unbecome, we can hot swap the actor functionality at runtime.
To step through this recipe, we need to import the Hello-Akka
project in the IDE-like IntelliJ Idea. Prerequisites are the same as those in previous recipes.
- Create a file named
BecomeUnbecome.scala
in packagecom.packt.chapter1
. - Add the following imports to the top of the file:
import akka.actor.{Props, ActorSystem, Actor}
- Define an actor which changes its behavior based on whether the state is
true
orfalse
, as shown in the following code:
class BecomeUnBecomeActor extends Actor { def receive: Receive = { case true => context.become(isStateTrue) case false => context.become(isStateFalse) case _ => println("don't know what you want to say !! ") } def isStateTrue: Receive = { case msg : String => println(s"$msg") case false => context.become(isStateFalse) } def isStateFalse: Receive = { case msg : Int => println(s"$msg") case true => context.become(isStateTrue) } }
- Create a test application,
BecomeUnBecomeApp
, as follows:
object BecomeUnBecomeApp extends App { val actorSystem = ActorSystem("HelloAkka") val becomeUnBecome = actorSystem.actorOf(Props[BecomeUnBecomeActor]) becomeUnBecome ! true becomeUnBecome ! "Hello how are you?" becomeUnBecome ! false becomeUnBecome ! 1100 becomeUnBecome ! true becomeUnBecome ! "What do u do?" }
- Run the application in an IDE like IntelliJ Idea or from the console; the output will be as follows:
Hello how are you? 1100 What do u do?
In step two, we define an actor, which changes its state to handle string and integer values.
If the state is true
, we set the behavior as context.become(isStateTrue)
, and it starts handling string messages. If the state is false
, we set the behavior as context.become(isStateFalse)
, and it starts handling integer messages.
In step four, we create the actor and send it to see if the output matches the functionality.