Sunday 20 December 2015

Promise in Scala


Promise

Where Future provides an interface exclusively for queryingPromise 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. 

Promise instance is always linked to exactly one instance of FutureOnce you have created a Promise, you can get the Future belonging to it by calling the future method on the Promise instance.

val taxcut: Promise[TaxCut] = Promise()

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.
  1. val p = promise[T]
  2. val f = p.future
  3. val producer = Future {
  4. val r = produceSomething()
  5. p success r
  6. continueDoingSomethingUnrelated()
  7. }
  8. val consumer = Future {
  9. f onSuccess {
  10. case r => doSomethingWithResult()
  11. }}

Note that the consumercan 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