简体   繁体   中英

Working with multiple Scala Futures

I've more than one Future .

val actor1 : Future[ActorRef] = createActorA()
val actor2 : Future[ActorRef] = createActorB() 
...
...
...

Now I need to extract the ActorRef s from all these futures so that I can use them to create a Router .

val routees = Vector[ActorRef](actor1, actor2, .....)
val router = system.actorOf(Props.empty.withRouter(
  RoundRobinRouter(routees = routees)))

I can call Await on each of these Future s to get the ActorRef . Is there is a better way ?

Use Future.sequence with foreach :

Future.sequence(Vector(
  createActorA(),
  createActorB() // and so on
)) foreach { routees =>
  val router = system.actorOf(Props.empty.withRouter(
    RoundRobinRouter(routees = routees)))
  // do something with router
}

Future.sequence takes a collection of futures and returns a future holding a collection with the result of those futures, in this case it returns Future[Vector[ActorRef]] . We then invoke foreach on this future to attach a handler to the completion of this future. This gives us access to the collection (the routees ) and we create the needed router. We can continue to do further processing in the function passed to foreach.

You may use for-comprehension.

val actors: Future[(ActorRef, ActorRef)] = for {
  a <- createActorA()
  b <- createActorB()
} yield (a -> b)
// Await on actors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM