More messages
Handling different messages is a fundamental aspect of working with actors in systems like Akka. Actors need to respond to various message types, each potentially requiring different handling logic. This capability allows actors to participate in complex workflows and maintain internal state accordingly.
Scala Example with Akka Typed
Akka Typed encourages more explicit and safer message handling by defining a protocol of messages an actor can handle. Let's look at a Scala example where an actor can handle different message types:
First, define a sealed trait (or an abstract class) that acts as a protocol for all messages the actor can receive. Then, implement case classes or case objects for each specific message:
import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.Behavior
sealed trait Message
final case class Greet(name: String) extends Message
final case class Configure(setting: String) extends Message
case object Shutdown extends Message
Next, define the actor behavior that matches against these messages:
object MyActor {
def apply(): Behavior[Message] = Behaviors.receive { (context, message) =>
message match {
case Greet(name) =>
context.log.info(s"Hello, $name!")
Behaviors.same
case Configure(setting) =>
context.log.info(s"Configuring with setting: $setting")
Behaviors.same
case Shutdown =>
context.log.info("Shutting down.")
Behaviors.stopped
}
}
}
Finally, create the actor system and send some messages to the actor:
object ActorSystemExample extends App {
val system: ActorSystem[Message] = ActorSystem(MyActor(), "myActorSystem")
system ! Greet("Akka")
system ! Configure("verbose")
system ! Shutdown
}