Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Fiddle {
- val f1 = Future {
- throw new Throwable("baaa") // emulating a future that bumped into an exception
- }
- val f2 = Future {
- Thread.sleep(3000L) // emulating a future that takes a bit longer to complete
- 2
- }
- val lf = List(f1, f2) // in the general case, this would be a dynamically sized list
- val seq = Future.sequence(lf)
- seq.onComplete {
- _ => lf.foreach(f => println(f.isCompleted))
- }
- }
- val a = FuturesSequence
- true
- false
- import scala.util.{ Failure, Success, Try }
- val lifted: List[Future[Try[Int]]] = List(f1, f2).map(
- _.map(Success(_)).recover { case t => Failure(t) }
- )
- import scala.util.{ Failure, Success, Try }
- private def lift[T](futures: Seq[Future[T]]) =
- futures.map(_.map { Success(_) }.recover { case t => Failure(t) })
- def waitAll[T](futures: Seq[Future[T]]) =
- Future.sequence(lift(futures)) // having neutralized exception completions through the lifting, .sequence can now be used
- waitAll(SeqOfFutures).map {
- // do whatever with the completed futures
- }
- try {
- val a = Await.result(Future.sequence(Seq(
- Future({
- blocking {
- Thread.sleep(5000)
- }
- System.err.println("A")
- 5
- }),
- Future({
- blocking {
- Thread.sleep(7000)
- }
- System.err.println("B")
- 7
- //throw new Exception("Ha!")
- }),
- Future({
- blocking {
- Thread.sleep(9000)
- }
- System.err.println("C")
- 9
- }))),
- Duration("100 sec"))
- System.err.println(a)
- } catch {
- case e: Exception ⇒
- e.printStackTrace()
- }
- def lift[T](f: Future[T])(implicit ec: ExecutionContext): Future[Try[T]] =
- f map { Success(_) } recover { case e => Failure(e) }
- def lift[T](fs: Seq[Future[T]])(implicit ec: ExecutionContext): Seq[Future[Try[T]]] =
- fs map { lift(_) }
- implicit class RichSeqFuture[+T](val fs: Seq[Future[T]]) extends AnyVal {
- def onComplete[U](f: Seq[Try[T]] => U)(implicit ec: ExecutionContext) = {
- Future.sequence(lift(fs)) onComplete {
- case Success(s) => f(s)
- case Failure(e) => throw e // will never happen, because of the Try lifting
- }
- }
- }
- val f1 = Future {
- throw new Throwable("baaa") // emulating a future that bumped into an exception
- }
- val f2 = Future {
- Thread.sleep(3000L) // emulating a future that takes a bit longer to complete
- 2
- }
- val lf = List(f1, f2)
- lf onComplete { _ map {
- case Success(v) => ???
- case Failure(e) => ???
- }}
Add Comment
Please, Sign In to add comment