The scala Future has a fromTry method which
Creates an already completed Future with the specified result or exception.
The problem is that the newly created Future is already completed. Is it possible to have the evaluation of the Try done concurrently?
As an example, given a function that returns a Try:
def foo() : Try[Int] = {
Thread sleep 1000
Success(43)
}
How can the evaluation of foo be done concurrently?
A cursory approach would be to simply wrap a Future around the function:
val f : Future[Try[Int]] = Future { foo() }
But the desired return type would be a Future[Int]
val f : Future[Int] = ???
Effectively, how can the Try be flattened within a Future similar to the fromTry method?
There is a similar question, however the question & answer wait for the evaluation of the Try before constructing the completed Future.
Future.delegate(Future.fromTry(foo()))- Luis Miguel Mejía Suárezdelegateisn't it. You are looking forFuture(foo.get)- DimaTryisSuccess, notFailure. - Ramón J Romero y Vigildelegateexecutes by-name argument on execution context. My swing:Future(foo()).flatMap(Future.fromTry)- Mario Galic