You can wait until the end using Await .
import scala.concurrent.duration._ import scala.concurrent.{Await, Future} val meaningOfLife: Int = Await.result(Future(42), 1.nano) println (meaningOfLife)
The above prints 42
You may need an implicit ExecutionContext , in which case just add:
import scala.concurrent.ExecutionContext.Implicits.global
Another way to do this is to use Coeval from monix . This method does not work in all situations, and you can read all about it here . The basic idea is that sometimes the future does not take much time and returns the result of a synchronous function or value call, so this future can be estimated in the current thread. It is also useful for testing and falsifying the future. In addition, you do not need to specify the expected timeout, but still it's nice not to worry about it.
You start by transforming the future into Task , then wrap this task in Coeval , and then cross your fingers, waiting for what you get. This is a very simple example to show how this works:
You need an implicit Scheduler to be able to use it:
import monix.execution.Scheduler.Implicits.global
Coeval(Task.fromFuture(Future (42)).runSyncStep).value() match { case Right(v) => println(v) case Left(task) => println("Task did not finish") }
The above ends and prints 42 to the console.
Coeval(Task.fromFuture(Future { scala.concurrent.blocking { 42 } }).runSyncStep).value() match { case Right(v) => println(v) case Left(task) => println("Task did not finish") }
This example prints Task did not finish :
smac89 Sep 23 '19 at 2:13 2019-09-23 02:13
source share