13.11. Switching Between Different States with become

Problem

You want a simple mechanism to allow an actor to switch between the different states it can be in at different times.

Solution

Use the Akka “become” approach. To do this, first define the different possible states the actor can be in. Then, in the actor’s receive method, switch between the different states based on the messages it receives.

The following example shows how the actor named DavidBanner might switch between its normalState and its angryState (when he becomes The Hulk):

package actortests.becometest

import akka.actor._

case object ActNormalMessage
case object TryToFindSolution
case object BadGuysMakeMeAngry

class DavidBanner extends Actor {
  import context._

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

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

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

object BecomeHulkExample extends App {
  val system = ActorSystem("BecomeHulkExample")
  val davidBanner = system.actorOf(Props[DavidBanner], name = "DavidBanner")
  davidBanner ! ActNormalMessage // init to normalState
  davidBanner ! TryToFindSolution
  davidBanner ! BadGuysMakeMeAngry
  Thread.sleep(1000)
  davidBanner ! ActNormalMessage
  system.shutdown
}

Here’s a ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.