有以下情况:
type LazyFuture = () => Future
val mainFuture: Future[Seq[LazyFuture]] = Future {
...
// some actions which can throw exceptions
...
// inner lazy futures as result of main future
// they has to be executed only if the main future is completed successfully
val xs: Seq[LazyFuture] = Seq(
() => Future(1),
() => Future(2),
...
() => Future(N)
)
xs
}
在mainFuture
成功执行的情况下,是否有方便执行内部懒惰期货的方法。以下伪说明了该任务:
val resultFuture:Future[Any] =
if(mainFuture is success)
// exec inner lazy futures
Future.sequence(mainFuture.result.map(c => c()))
else
// nothing
Future.successful(Unit)
答案 0 :(得分:0)
我为上述任务找到了以下解决方案。
type LazyFuture = () => Future
val mainFuture: Future[Seq[LazyFuture]] = Future {
val xs: Seq[LazyFuture] = Seq(
() => Future(1),
() => Future(2),
...
() => Future(N)
)
xs
}
val promise = Promise[Future[Seq[Any]]]()
mainFuture.onComplete {
case Success(xs: Seq[LazyFuture]) =>
val eventualSeq: Future[Seq[Any]] = Future.sequence(xs.map(c => c()))
promise success eventualSeq
case Failure(t) => promise failure t
}
val resultFuture: Future[Any] = promise.future.flatten
此解决方案是否足够好并且可能出现任何问题?