Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Last active October 21, 2020 12:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryanlecompte/6313683 to your computer and use it in GitHub Desktop.
Save ryanlecompte/6313683 to your computer and use it in GitHub Desktop.
sequential futures!
def performSequentially[A](items: Seq[A])(f: A => Future[Unit]): Future[Unit] = {
items.headOption match {
case Some(nextItem) =>
val fut = f(nextItem)
fut.flatMap { _ =>
// successful, let's move on to the next!
performSequentially(items.tail)(f)
}
case None =>
// nothing left to process
Future.successful(())
}
}
scala> val items = 0 to 5
items: scala.collection.immutable.Range.Inclusive = Range(0, 1, 2, 3, 4, 5)
scala> performSequentially(items) { i => future { Thread.sleep(10000); println("hello " + i) } }
res0: scala.concurrent.Future[Unit] = scala.concurrent.impl.Promise$DefaultPromise@250f9a46
// you will see the above output every 10 seconds, not at the same time!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment