TLDR:
Inject the parent actor reference into the child when creating it.
Akka Typed enforces strict protocols, so you need to make it absolutely clear that "this actor talks to another actor". The accepted answer is a workaround (casting to classic and using the parent), but has its downsides: now you do not enforce types anymore.
Here is some code that should get you started. See how all the types are enforced. You can model the traits differently, but you should get the drift:
object ParentActor {
sealed trait Command
case class DoSomething() extends Command
// you do not have to do this, but creating another trait
// allows you to narrow the amount of messages the parent can receive from the child
sealed trait ChildNotification extends Command
case class MessageFromChild() extends ChildNotification
def apply(): Behavior[Command] = {
Behaviors.receive( (context, message) =>
message match {
case DoSomething() =>
// create a child that knows about its parent
context.spawn(ChildActor(context.self), "child")
Behaviors.same
case MessageFromChild() =>
context.log.info("I received a message from my child")
Behaviors.same
})
}
}
object ChildActor {
sealed trait Command
case class Work() extends Command
// inject the parent here (or any other actor that matches the signature)
def apply(parent: ActorRef[ParentActor.ChildNotification]): Behavior[Command] = {
Behaviors.receive( (context, message) =>
message match {
case Work() =>
// send message to parent actor (or any other actor with that type)
parent ! ParentActor.MessageFromChild()
Behaviors.same
})
}
}
By the way, I am using the "functional" syntax of akka typed, but you can use the more "object-oriented" syntax as well. It follows the same approach.
javadsl
orscaladsl
depending on the language: thus the best answer for doing something in Java and doing something in Scala are quite possibly going to be different (albeit similar). – Daisakka-actor
tag withakka-typed
. Basically, the classic Akka actor API still exists in 2.6 (and the Java in the answers in the target answer also works directly in Scala), but if using the typed API to describe an actor's behavior, no answer in the target would work. – Dais