Skip to content

Instantly share code, notes, and snippets.

@lukas-mi
Last active March 22, 2018 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukas-mi/8beaae1f614fc9c4c72a1dfc0bb93944 to your computer and use it in GitHub Desktop.
Save lukas-mi/8beaae1f614fc9c4c72a1dfc0bb93944 to your computer and use it in GitHub Desktop.
Convert list of futures to future of list of successes and future of list of failures (List[Future[T]] to (Future[List[T]], Future[List[Throwable]]))
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}
object FutureHelper {
def partition[T](futures: List[Future[T]])(implicit executor: ExecutionContext): (Future[List[T]], Future[List[Throwable]]) = {
val futuresOfTry: List[Future[Try[T]]] = futures.map(_.transform(Success(_)))
val successes = Future.sequence(futuresOfTry)
.map(_.collect { case Success(x) => x })
val failures = Future.sequence(futuresOfTry)
.map(_.collect { case Failure(x) => x })
(successes, failures)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment