Skip to content

Instantly share code, notes, and snippets.

@SamirTalwar
Created February 20, 2020 15:43
Show Gist options
  • Save SamirTalwar/7eff96355085e81aa2ab2b393453b32f to your computer and use it in GitHub Desktop.
Save SamirTalwar/7eff96355085e81aa2ab2b393453b32f to your computer and use it in GitHub Desktop.
Serially execute a list of futures, in Scala. I find myself writing this fairly often, typically for testing or debugging.
object Serially {
def apply[T, U](values: Seq[T])(body: T => Future[U])(implicit executionContext: ExecutionContext): Future[List[U]] =
apply(values.toList)(body)
def apply[T, U](values: List[T])(body: T => Future[U])(implicit executionContext: ExecutionContext): Future[List[U]] =
values match {
case Nil =>
Future.successful(List.empty)
case head :: tail =>
body(head).flatMap(headResult =>
apply(tail)(body).map(tailResult =>
headResult :: tailResult))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment