Search code examples
akkawildcardactor

Selecting all akka actors in a subtree with ActorSelection wildcard


The akka documentation explains how it is possible to use wildcards when using ActorSelection (http://doc.akka.io/docs/akka/snapshot/general/addressing.html#Querying_the_Logical_Actor_Hierarchy).

The following code will send a message to all actors directly under /user

context.actorSelection("/user/*") ! msg

Is it possible to use a wildcard that would send a message to all descendants (not only direct children) in an actor hierarchy? I have tried the following code, without success:

context.actorSelection("/**") ! msg

Solution

  • No, we do not support "send to all descendants, however many levels deep". I feel that this could easily lead to unexpected behaviour and may be overused. You can do something similar, but with specifying the depth of the search, as in:

    val top = system.actorOf(p, "a")
    val b1 = Await.result((top ? Create("b1")).mapTo[ActorRef], timeout.duration)
    val b2 = Await.result((top ? Create("b2")).mapTo[ActorRef], timeout.duration)
    val c = Await.result((b2 ? Create("c")).mapTo[ActorRef], timeout.duration)
    val d = Await.result((c ? Create("d")).mapTo[ActorRef], timeout.duration)
    
    system.actorSelection("/user/a/*/c/*").tell(Identify(6), probe.ref)
    probe.expectMsg(ActorIdentity(6, Some(d)))
    probe.expectNoMsg(200.millis)
    

    Also, actor selection is possibly not what you're after and instead you could use something that's dedicated for broadcasting like that;

    You could use the EventStream and publish your broadcast there.

    Or if you're in a clustered env use the DistributedPubSub extension (here's an activator template with it: akka-clustering (pubsub) activator template)