Home > Enterprise >  How to block the thread and get Try[A] from Future[A]?
How to block the thread and get Try[A] from Future[A]?

Time:06-15

I have List[Future[A]]. I'd like to block my thread and get List[Try[A]] "right now". Can't find a nice solution.

CodePudding user response:

You can use Await: https://www.scala-lang.org/api/2.13.3/scala/concurrent/Await$.html

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.Try

val res = Try(Await.result(someFuture, 10.seconds))

That said, blocking is rarely a good idea. Futures are meant to be composed with methods such as flatMap.

CodePudding user response:

Now that you have clarified your question (in the comment to my other answer), here's one possibility to do it:

import scala.util._
import scala.concurrent._

def partitionFutures[A](
  l: List[Future[A]])(
  implicit ec: ExecutionContext
): Future[(List[A], List[Throwable])] = {
  Future.traverse(l)(f => f.transform(Success.apply)).map { trys =>
    val as = trys.collect { case Success(a) => a }
    val errs = trys.collect { case Failure(err) => err }
    as -> errs
  }
}

The type isn't quite the same as the one you proposed, but it's unclear why you would want a list of pairs of lists, so I simplified it to a pair of lists.

  • Related