blue-sky
blue-sky

Reputation: 53856

Akka parent not receiving message from child

Below akka hierarchy is a parent child where the parent sends a message to the child and the child responds with value 1. But the parent does not appear to receive the value as the message "received is 1" is not printed to console.

Is my hierarchy setup correctly ? :

import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props

class ChildActor extends Actor {
  def receive = {
    case receivedValue: Int => {
      println(receivedValue);
      context.parent ! 1
    }
  }
}

object ParentChild extends App {

  val system = ActorSystem()

  val parentActor = system.actorOf(Props[ParentActor])

  class ParentActor extends Actor {

    val childActor = system.actorOf(Props[ChildActor])
    childActor ! 1
    def receive = {
      case v: Int => println("received is " + v);
    }

  }

}

Upvotes: 1

Views: 417

Answers (1)

Qingwei
Qingwei

Reputation: 510

Because you created the childActor using

val childActor = system.actorOf(Props[ChildActor])

Which means it is a top-level actor, it's parent is ActorSystem instead of the ParentActor which you would expect

To have it work as expect, you need to create ChildActor as follow

val childActor = context.actorOf(Props[ChildActor])

inside ParentActor

Upvotes: 4

Related Questions