Saturday, 11 July 2015

Switching Between Different States with Become

The general recipe for using the become approach to switch between different possible states is:
  • Define the different possible states
  • Define the receive method in the actor to switch to the different states based on the messages it can receive. 
It’s important to note that the different states can only receive the messages they’re programmed for, and those messages can be different in the different states.
It's very common for an Actor to be in a state where it can't process certain messages. Akka has a mechanism called stash. Stashing messages puts the message off to the side in a separate queue that it cannot currently handle. Unstash puts the message that were set aside back into the mailbox queue for the actor to handle.
If the connect message takes too long to be received, or is not received, then messages will continually be stashed until the application runs out of memory or the mailbox starts dropping messages. Schedule a timeout message to be sent to the actor after a certain period of time.

system.scheduler().scheduleOnce(Duration.create(1000,TimeUnitMILLISECONDS), self(),
CheckConnected, system.dispatcher(), null);
class DavidBanner extends Actor {
  import context._

  def angryState: Receive = {
    case ActNormalMessage =>
         println("Phew, I'm back to being David.")

  def normalState: Receive = {
    case TryToFindSolution =>
         println("Looking for solution to my problem ...")
    case BadGuysMakeMeAngry =>
         println("I'm getting angry...")

  def receive = {
    case BadGuysMakeMeAngry => become(angryState)
    case ActNormalMessage => become(normalState)

No comments:

Post a Comment