Promise
Where
Future
provides an interface exclusively for querying, Promise
is a companion type that allows you to complete a Future
by putting a value into it. This can be done exactly once. Once a Promise
has been completed, it’s not possible to change it any more.
A
Promise
instance is always linked to exactly one instance of Future
. Once you have created a Promise
, you can get the Future
belonging to it by calling the future
method on the Promise
instance.val taxcutF: Future[TaxCut] = taxcut.future
taxcut.success(TaxCut(20))
To complete a
Promise
with a success, you call its success
method, passing it the value that the Future
associated with it is supposed to have.
Also, completing your
Promise
like this leads to the successful completion of the associated Future
.
Usually, the completion of the
Promise
and the processing of the completed Future
will not happen in the same thread. It’s more likely that you create your Promise
, start computing its value in another thread and immediately return the uncompleted Future
to the caller.
That is, a promise can be used to successfully complete a future with a value using the
success
method. Conversely with an exception, by failing the promise, using the failure
method.val p = promise[T]
val f = p.future
val producer = Future {
val r = produceSomething()
- p success r
- continueDoingSomethingUnrelated()
}
val consumer = Future {
f onSuccess {
case r => doSomethingWithResult()
}
}
Note that the
consumer
can obtain the result before the producer
task is finished executing thecontinueDoingSomethingUnrelated()
method.
Reference:
http://danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html
No comments:
Post a Comment