Creating an empty Scala Future to be completed externally

Is it possible / how to create an empty Future, set the necessary callbacks for its completion, and then set its result at a different point in time? In pseudocode (uncompilable) that would look like the following:

val future: Future[Int] = Future.empty()
future.onComplete {
  case Failure(exception) => 
    println(s"Exception: $exception")
  case Success(value) =>
    println(s"Done: $value")
// from a different thread at some point in the future

>Solution :

You are looking for the Promise.

val promise = Promise[Int]()
val future = promise.future
future.onComplete { ... } 


Leave a Reply