Executing sequence of functions that return a future sequentially

时间:2016-03-04 17:46:53

标签: scala twitter-util

I have a sequence of functions that return a future. I want to execute them sequentially i.e. after the first function future is complete, execute the next function and so on. Is there a way to do it?

ops: Seq[() => Future[Unit]]

3 个答案:

答案 0 :(得分:4)

您可以将所有期货合并为一个foldLeftflatMap

def executeSequentially(ops: Seq[() => Future[Unit]])(
  implicit exec: ExecutionContext
): Future[Unit] =
  ops.foldLeft(Future.successful(()))((cur, next) => cur.flatMap(_ => next()))

foldLeft确保从左到右的顺序,flatMap给出顺序执行。函数使用ExecutionContext执行,因此调用executeSequentially不会阻塞。如果需要,您可以在结果Future上添加回调或等待。

如果您使用Twitter Future,那么我猜您不会需要通过ExecutionContext,但foldLeftflatMap的一般想法应该是还在工作。

答案 1 :(得分:2)

如果给定Seq [Future [T]],你可以将它转换为Future [Seq [T]],如下所示:

Val a: Seq[Future[T]] = ???

val resut: Future[Seq[T]] = Future.sequence(a)

比以上更少的样板:)

答案 2 :(得分:0)

我相信应该这样做:

import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration

def runSequentially(ops: Seq[() => Future[Unit]]): Unit = {
  ops.foreach(f => Await.result(f(), Duration.Inf))
}

如果你想等到Duration.Inf以下,或者在失败时停止 - 应该很容易做到。