Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 305
Shankar Avatar asked Sep 01 '16 03:09

Shankar


2 Answers

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.

like image 94
Federico Avatar answered Sep 22 '22 16:09

Federico


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))
like image 35
sarveshseri Avatar answered Sep 19 '22 16:09

sarveshseri