创造未来而不启动它

Mic*_*ael 8 concurrency scala future

这是我上一个问题的后续行动

假设我想用我的函数创建一个未来,但不想立即启动它(即我不想打电话val f = Future { ... // my function}.

现在我看到它可以按如下方式完成:

val p = promise[Unit]
val f = p.future map { _ => // my function here }

这是用我的函数创建未来的唯一方法吗?

Mar*_*ila 7

你可以做这样的事情

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

//... some code run at a later time
p.success {
// your function
}
Run Code Online (Sandbox Code Playgroud)

后期编辑:

我认为您正在寻找的模式可以像这样封装:

class LatentComputation[T](f: => T) {
  private val p = Promise[T]()

  def trigger() { p.success(f) }

  def future: Future[T] = p.future
}

object LatentComputation {
  def apply[T](f: => T) = new LatentComputation(f)
}
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

val comp = LatentComputation {
// your code to be executed later
}

val f = comp.future

// somewhere else in the code
comp.trigger()
Run Code Online (Sandbox Code Playgroud)