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]]
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]]
I believe this should do it:
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))
}
If you want to wait less then Duration.Inf
, or stop at failure - should be easy to do.
You can combine all the futures into a single one with a
foldLeft
andflatMap
:foldLeft
ensures the order from left to right andflatMap
gives sequential execution. Functions are executed with theExecutionContext
, so callingexecuteSequentially
is not blocking. And you can add callbacks or await on the resultingFuture
when/if you need it.If you are using Twitter
Future
s, then I guess you won't need to passExecutionContext
, but the general idea withfoldLeft
andflatMap
should still work.