tano
tano

Reputation: 896

akka - get list of ActorRef from ActorSelection

ActorSelection support wildcard and it allows to send a message to all actors that match the selection:

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

Is there a way to retrieve the list of ActorRef that match the selection from the ActorSelection? From the documentation I can see that there is a resolveOne function but not (for example) a resolveList.

Update

The reason why I want the list of ActorRef is that I would like to use the ask operator on all the actors that match the selection.

Just to be clear here is an example of what I would like to do:

object MyActor {
  case object AskAllActors
  case object GetActorInfo
}

class MyActor extends Actor {
  import MyActor._

  def receive = {
    case AskAllActors =>
      val actors: List[ActorRef] = context.actorSelection("../*").resolveList()
      val result: List[Future[String]] = actors.map { a => (a ? GetActorInfo).mapTo[String] }
      Future.sequence(result).map { result =>
        // do something with result: List[String]
      }
  }
}

Upvotes: 2

Views: 1731

Answers (1)

The ability to get a list of the form

val timeout : FiniteDuration = 10 seconds

val actorList = actorSelection.resolveMany(timeout)

does not exist. I suspect the reason is because once the timeout expires there is a chance that an Iterable, of non-zero length, is returned but it would be impossible to know if the Iterable is comprehensive. Some Actors may not have had enough time to respond. With resolveOne the issue does not exist, the first responding ActorRef is the result.

Based on the documentation it looks like you could use the Identify message to have all of the Actors specified in an actorSelection respond with identification:

class Follower extends Actor {
  val identifyId = 1
  context.actorSelection("../*") ! Identify(identifyId)

  def receive = {
    case ActorIdentity(`identifyId`, Some(ref)) => ...
  }
}

Upvotes: 1

Related Questions