【发布时间】:2015-05-17 23:18:25
【问题描述】:
我有一个 akka 演员,其中我在 scala 中有几个期货,它们只做一些额外的工作并将计算保存到共享变量中。主要工作完成后,我想等待这些“额外”的未来并回复一个答案。简单的代码是这样的:
....
val replyTo = sender()
var informationCollector = InformationCollector()
val mainFuture: Future[GetMainInformation] = ...
val aFuture: Future[GetExtraInformationA] =...
val bFuture: Future[GetExtraInformationB] =...
val cFuture: Future[GetExtraInformationC] =...
// now I want all the futures to write their result
// and save it into the informationCollector and then
// after all have executed, reply back to Sender all the collected Data.
使用这种方法,我有 2 个问题。我不确定在期货的 onSuccess 调用中访问 InformationCollector 是否安全,我也想让它易于扩展(因此可以轻松添加其他收集器)。
到目前为止,我想出了这个解决方案,但我不确定它是否正确
// IMPORTANT: firstly add map for all of the extraInfoFutures to add that information into collector
// this will create aFutureMapped, bFutureMapped, cFutureMapped
roomFuture onComplete {
case Success(mainInfo: GetMainInformation) => {
informationCollector = informationCollector.copy(mainInformation=mainInfo)
Future.sequence(List(aFutureMapped,bFutureMapped,cFutureMapped)) onComplete { _ =>
replyTo ! informationCollector
}
}
}
非常感谢任何帮助。
【问题讨论】: