Difference between Future Callback Methods and Promises? Success and Failure?

I cant Scala Concurrencyuse Futureand Promises.

I don’t understand what is the exact difference between completing the future using methods Callbackand using Promises?

Does this mean that future callback methods do not actually complete the future? Only using a promise can we complete the future?

In addition, I saw a lot of places where you can read with both futures and Promises, but you can only write Promises.

+4
source share
3 answers

Futures end only at the end of the asynchronous calculation:

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")
}

Promises , .

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")
}

, onSuccess, , , - . Promises success .

+3

complete a Future.

A Future , ( ) , . . onComplete, , , , .

Future, , Promise, Future . , , .

// 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(10)
+3

In fact, you are not completing Future, you are simply passing a callback to start when at the final stage. You can use Promiseto control when a callback will be called. Example from scala white papers:

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

val producer = Future {
  val r = produceSomething()
  p success r
  continueDoingSomethingUnrelated()
}

btw Futureusing Promisesunder the hood.

0
source

Source: https://habr.com/ru/post/1653235/


All Articles