Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Try to Future and recoverWith as Future

I have a Try that throws Exception. I want that Try to become a Future so I will be able to recoverWith.

How can I convert the Try into a Future without handling any exceptions in the Try (just in the Future with recover)?

note that Await is needed to test the result of your future

The code sample demonstrates what I had in mind but it also throws once reached (new RuntimeException("-------failed-------") is what I get)

val t = Try(throw new RuntimeException("my"))

val resF : Future[String] = if (t.isSuccess)
  Future.successful(t.get)
else
  Future.failed(new RuntimeException("-------failed-------"))

val resFWithRecover = resF.recoverWith{
  case NonFatal(e) =>
    Future.successful("recoveredWith")
}
Await.result(resFWithRecover, Duration("5s"))
like image 535
ozma Avatar asked Sep 19 '16 20:09

ozma


People also ask

How do you create a Future in Scala?

The simplest way to create a future object is to invoke the Future. apply method which starts an asynchronous computation and returns a future holding the result of that computation. The result becomes available once the future completes.

What Future sequence does?

This Future. sequence() function converts a list of Futures into a single Future that means collections of Futures into a single Future. In simple words, List[Future[T]] ======> Future[List[T]] . It is also known as composing Futures.

How do Scala Futures work?

Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.

What is recover in Scala?

recover allows you to emit a final element and then complete the stream on an upstream failure. Deciding which exceptions should be recovered is done through a PartialFunction . If an exception does not have a matching case the stream is failed.


1 Answers

... how do convert Try to Future without handling any exception in the Try?

Use Future.fromTry.

scala> val t = Try(throw new RuntimeException("my"))
t: scala.util.Try[Nothing] = Failure(java.lang.RuntimeException: my)

scala> val resF = Future.fromTry(t)
resF: scala.concurrent.Future[Nothing] = scala.concurrent.impl.Promise$KeptPromise@57cf54e1

scala> resF.recoverWith{
     |   case NonFatal(e) =>
     |     Future.successful("recoveredWith")
     | }
res5: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@1b75c2e3
like image 72
Michael Zajac Avatar answered Sep 23 '22 02:09

Michael Zajac