Created
September 13, 2016 20:16
-
-
Save dportabella/caa101e577824a0f42975d427630f715 to your computer and use it in GitHub Desktop.
Example on how to execute scala futures in serial one after the other, without collecting the result of the futures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example on how to execute scala futures in serial one after the other, without collecting the result of the futures | |
Look this instead if we need to collect the result of the futures (it also explains how foldLeft works here): | |
https://gist.github.com/dportabella/4e7569643ad693433ec6b86968f589b8 | |
*/ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.{Await, ExecutionContext, Future} | |
object ExampleExecuteScalaFuturesInSerial extends App { | |
def myFuture(i: Int) = Future { | |
Thread.sleep(1000) | |
val s = s"done: $i" | |
println(s) | |
} | |
def serialiseFutures[A](list: Iterable[A])(fn: A => Future[Unit])(implicit ec: ExecutionContext): Future[Unit] = { | |
val zero = Future(()) | |
list.foldLeft(zero) { (accFuture, nextItem) => | |
accFuture.flatMap(_ => { | |
val nextFuture = fn(nextItem) | |
nextFuture | |
}) | |
} | |
} | |
def task = serialiseFutures(List(10, 20, 30)) { i => myFuture(i) } | |
Await.result(task, Duration.Inf) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment