Creating child actors of a parent actor
In this recipe, we will learn how to create child actors of an actor. Akka follows a tree-like hierarchy to create actors and it is also the recommended practice.
By following such practices, we can handle failures in actors as the parent can take care of it. Lets see how to do it.
Getting ready
We need to import the Hello-Akka
project in the IDE of our choice. The Akka actor dependency that we added in build.sbt
is sufficient for most of the recipes in this chapter, so we will skip the Getting ready section in our further recipes.
How to do it...
- Create a file named
ParentChild.scala
in packagecom.packt.chapter2
. - Add the following imports to the top of the file:
import akka.actor.{ActorSystem, Props, Actor}
- Create messages for sending to actors.
case object CreateChild case class Greet(msg: String)
- Define a child actor as follows:
class ChildActor extends Actor { def receive = { case Greet(msg) =>...