How to concurrently create Future from Try?

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.

Upvotes: 3

Views: 314

Answers (2)

Viktor Klang
Viktor Klang

Reputation: 26579

Least ceremony is probably:

Future.unit.transform(_ => foo())

Special mention goes to @Dima for the suggestion of Future(foo().get) which is a bit shorter—but might be slightly less readable.

Upvotes: 3

Based on the comments,

Scala >= 2.13:

val f : Future[Int] = Future.delegate(Future.fromTry(foo()))

Scala < 2.13:

val f : Future[Int] = Future(foo()).flatMap(Future.fromTry)

Upvotes: 3

Related Questions