Last active
August 17, 2020 10:56
-
-
Save akkomar/04945b5f0384717917f8 to your computer and use it in GitHub Desktop.
Merging sequence of Futures of Lists into one Future containing merged list
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
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import scala.concurrent.{Await, Future} | |
val futures: List[Future[List[Int]]] = | |
List.fill(10)(Future { | |
Thread.sleep(100) | |
List(1, 2, 3) | |
}) | |
// def merge[T](first: Future[Seq[T]], second: Future[Seq[T]]): Future[Seq[T]] = | |
// for { | |
// a <- first | |
// b <- second | |
// } yield a ++ b | |
// val future: Future[Seq[Int]] = futures.foldLeft(Future(List[Int]()):Future[Seq[Int]])( | |
// (acc, fut) => merge(acc, fut)) | |
// even better: | |
val future: Future[List[Int]] = Future.fold(futures)(List[Int]())((acc, e) => acc ++ e) | |
Await.result(future, 1 second) |
Future.sequence(futures) map { _.flatten }
what if one of the future got blocked and never returned anything, how to handle this scenario?
what if one of the future got blocked and never returned anything, how to handle this scenario?
=> use promise is this situation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This worked flawlessly for my problem. I kept trying to force a labyrinth of maps, but the fold is an interesting new function I have not used. Kudos!