创建一个空的Scala Future,以便外部完成。

huangapple go评论53阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月9日 22:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定