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

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

Creating an empty Scala Future to be completed externally

问题

有可能吗/如何创建一个空的 Future,为其完成设置必要的回调,然后在不同的时间点设置其结果?在伪代码(无法编译)中,看起来像这样:

  1. val future: Future[Int] = Future.empty()
  2. future.onComplete {
  3. case Failure(exception) =>
  4. println(s"异常:$exception")
  5. case Success(value) =>
  6. println(s"完成:$value")
  7. }
  8. // 在将来的某个时间点,来自不同的线程
  9. 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:

  1. val future: Future[Int] = Future.empty()
  2. future.onComplete {
  3. case Failure(exception) =>
  4. println(s"Exception: $exception")
  5. case Success(value) =>
  6. println(s"Done: $value")
  7. }
  8. // from a different thread at some point in the future
  9. future.set(123)

答案1

得分: 3

你正在寻找Promise

  1. val promise = Promise[Int]()
  2. val future = promise.future
  3. future.onComplete { ... }
  4. promise.success(123)
英文:

You are looking for the Promise.

  1. val promise = Promise[Int]()
  2. val future = promise.future
  3. future.onComplete { ... }
  4. 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:

确定