Last active
October 21, 2020 12:32
-
-
Save ryanlecompte/6313683 to your computer and use it in GitHub Desktop.
sequential futures!
This file contains hidden or 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
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