[英]Working with multiple Scala Futures
I've more than one Future
. 我有不止一个
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
. 现在我需要从所有这些期货中提取
ActorRef
,以便我可以使用它们来创建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
. 我可以打电话给
Await
在这些的Future
s到获得ActorRef
。 Is there is a better way ? 有更好的方法吗?
Use Future.sequence
with foreach
: 在
foreach
使用Future.sequence
:
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]]
. Future.sequence
收集期货的集合并返回一个包含这些期货结果的集合的未来,在这种情况下它返回Future[Vector[ActorRef]]
。 We then invoke foreach
on this future to attach a handler to the completion of this future. 然后我们在这个未来调用
foreach
来附加一个处理程序来完成这个未来。 This gives us access to the collection (the routees
) and we create the needed router. 这使我们可以访问集合(
routees
),并创建所需的路由器。 We can continue to do further processing in the function passed to foreach. 我们可以继续在传递给foreach的函数中进行进一步处理。
You may use for-comprehension. 你可以使用for-understanding。
val actors: Future[(ActorRef, ActorRef)] = for {
a <- createActorA()
b <- createActorB()
} yield (a -> b)
// Await on actors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.