Created
February 20, 2020 15:43
-
-
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.
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
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