'Scala Akka broadcasting send message to all child actors from Parent Context
In my task parent actor create some child actors and send message to them
def apply(): Behavior[CreateBranch] = {
Behaviors.receive { (context, message) =>
val child1 = context.spawn(Child(), "child1")
val child2 = context.spawn(Child(), "child2")
val child3 = context.spawn(Child(), "child3")
context.children.foreach {
child ! Child.SomeMessage
{
}
}
Child actor defined as:
object Child {
sealed trait SomeMessage
def apply():Behavior[SomeMessage] = {
// some behaviour
{
}
But expression "context.children" does not work: children defined as Iterable[ActorRef[Nothing]] instead of Iterable[ActorRef[Child.SomeMessage]]
In documentation about "context.children" ActorContext.children
"this is not a useful way to lookup children when the purpose is to send messages to them."
And this document suggest alternative way of realisation - but it about of 30 lines of code!
Is there any other alternative way to realise broadcast message send ?
Solution 1:[1]
You asked "Is there any other alternative way to realise broadcast message send ?".
Levi's answer is the most technically correct. But I think the "real" answer is not to use context.children. This complication is caused by the type system trying to protect you from something that is a very legitimate concern. That collection contains ALL children. And there are lots of times I might spawn a child just to monitor a timeout, receive a single message, or some other task that might not understand that message.
If you want to send a specific message to child actors, as was pointed out in Levi's answer, you probably don't really mean "all child actors", you mean "all child actors who understand this message". And although there are some other ways you could do this, I always find it easiest just to maintain your own collection of ActorRefs for an actor of a particular type. If I have "worker actors" I maintain my own sequence and then the message types just work automagically.
My experience is that you should really only use context.children for system-type operations. But anything else, I maintain my own collection. That way if I create a new type of child actor at a later date, I don't break any assumptions I'm making about the type of child actors and what messages they can receive.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Ogren |
