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.
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.
You can not complete
a Future
.
A Future
is supposed to be a computation and this computation (once started) completes when it does. You have no control over it after creating it. You can assign onComplete
callback to it which will be fired when this future completes but you have no control over when it will.
If you want to have a Future
whose completion you can control, you can Promise
that Future
like a politician. Now whether you complete that future with success or failure is up to you.
// lets promise an Int
val promise = Promise[Int]()
// Now... we also have a future associated with this promise
val future = promise.Future
// assign a callback which will be called when future completes
future.onComplete(
case Success(i) => println("Future complete :: " + i)
case Failure(ex) => println("Future failed :: " + ex.toString)
)
// Future by itself provides you no way to complete it
// if you want to complete this future, you can fulfil your promise
promise.complete(Try(10))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With