英文:
Creating an empty Scala Future to be completed externally
问题
有可能吗/如何创建一个空的 Future,为其完成设置必要的回调,然后在不同的时间点设置其结果?在伪代码(无法编译)中,看起来像这样:
val future: Future[Int] = Future.empty()
future.onComplete {
case Failure(exception) =>
println(s"异常:$exception")
case Success(value) =>
println(s"完成:$value")
}
// 在将来的某个时间点,来自不同的线程
future.set(123)
英文:
Is it possible / how to create an empty Future, set the necessary callbacks for its completion, and then set its result at a different point in time? In pseudocode (uncompilable) that would look like the following:
val future: Future[Int] = Future.empty()
future.onComplete {
case Failure(exception) =>
println(s"Exception: $exception")
case Success(value) =>
println(s"Done: $value")
}
// from a different thread at some point in the future
future.set(123)
答案1
得分: 3
你正在寻找Promise。
val promise = Promise[Int]()
val future = promise.future
future.onComplete { ... }
promise.success(123)
英文:
You are looking for the Promise.
val promise = Promise[Int]()
val future = promise.future
future.onComplete { ... }
promise.success(123)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论