Will Will - 1 year ago 70
Scala Question

I can't get a child actor to receive messages

I'm new to akka and I'm wondering how to get a child actor to receive messages.

I have one parent actor which prints out that it received a message and then sends a message to its child which then prints out that it received a message.

When I run the program, only the parent actor prints its message. Is there
something I'm missing?

The parent actor

class TestDirector(name: String) extends Actor {
import TestDirector._

implicit val timeout = Timeout(5.seconds)

private var child: ActorRef = _

override def preStart(): Unit = {
println(name + " pre-start")
child = context.actorOf(props("test-file"), name = "child-actor")

override def receive: Receive = {
case TestDirectory(dir) =>
println("Test Director")
child ! TestWorker.TestFile


object TestDirector {
case class TestDirectory(dirName: String)
case class TestResponse(message: String)

def props(dirName: String) = Props(classOf[TestDirector], dirName)


The child actor

class TestWorker(fileName: String) extends Actor {
import TestWorker._

override def receive: Receive = {
case TestFile => println("Hello world")


object TestWorker {
case object TestFile

def props(fileName: String) = Props(classOf[TestWorker], fileName)

Answer Source

In TestDirector.preStart, you say

    child = context.actorOf(props("test-file"), name = "child-actor")

Those "props" are TestDirector.props, which you imported a few lines above, so you're endlessly creating new TestDirectors. I think what you want instead is TestWorker.props:

    child = context.actorOf(TestWorker.props("test-file"), name = "child-actor")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download