Ramesh Ramesh - 3 months ago 23
Scala Question

Difference between Future callback methods and Promises [Success and Failure]?

I am leaning

Scala Concurrency
using
Future
and
Promises
.

I am not getting the point, what is the exact difference between completing the Future using
Callback
methods and using Promises?

Does it mean Future Callback methods are actually not completing the Future?Only using Promise we can complete the Future?

Also, I have seen many places like you can read from both Futures and Promises, but you can only write to Promises.

Answer

Futures are only completed on the end of an asynchronous computation:

val f: Future[List[Int]] = Future {
  makeSomeNumbers() //when this finishes, the Future is completed.
}

f onSuccess {
  case foo => println("I was completed when makeSomeNumbers finished")
}

Whereas Promises can produce a future that can be completed manually.

val p = Promise[String]()
val f = p.future

p success('hi') //when success is called, the Future is completed.

f onSuccess {
  case foo => println("I was completed because a Promise told me to do so")
}

The callback passed to onSuccess does not complete the Future, it only listens when the Future is completed and does something. In the case of Promises, you can call its success method to complete its associated Future.