我用Future
和Promises
学习Scala Concurrency
我不明白,使用Callback
方法和使用promise完成Future之间的确切区别是什么?
这是否意味着未来回调方法实际上没有完成未来?只有用承诺我们才能完成未来?
而且,我也看到过很多地方,你可以从"未来"one_answers"承诺"中读到,但你只能写"承诺"。
期货只在异步计算结束时完成:
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")
}
而promise可以生成一个可以手动完成的未来。
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
的回调不会完成Future,它只在Future完成时侦听并做一些事情。对于Promises,你可以调用它的success
方法来完成它关联的Future。
你不能complete
a Future
。
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(Try(10))
您实际上没有完成 Future
,您只是在完成时传递回调以触发。你可以使用Promise
来控制何时触发回调。示例来自scala官方文档:
val p = Promise[T]()
val f = p.future
val producer = Future {
val r = produceSomething()
p success r
continueDoingSomethingUnrelated()
}
btw Future
using Promises
under the hood.