【问题标题】:In Scala, why is there no implementation for `Future.onComplete`?在 Scala 中,为什么没有“Future.onComplete”的实现?
【发布时间】:2023-03-19 04:33:01
【问题描述】:

Future模块的source code中,我看到onComplete的定义是这样的:

  /** When this future is completed, either through an exception, or a value,
   *  apply the provided function.
   *
   *  If the future has already been completed,
   *  this will either be applied immediately or be scheduled asynchronously.
   *
   *  $multipleCallbacks
   *  $callbackInContext
   */
  def onComplete[U](@deprecatedName('func) f: Try[T] => U)(implicit executor: ExecutionContext): Unit

这看起来很奇怪,因为它没有函数体(没有实现)。那么为什么onComplete 可以工作呢?它是用Java实现的吗?如何找到真正的实现代码?

【问题讨论】:

    标签: scala concurrency akka future


    【解决方案1】:

    再深入一点。您通常如何创建Future?一种方法是Future.apply

    What does it do?

     def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)
    

    impl.Future.apply 创建一个 PromiseCompletingRunnable,其中包含一个 Promise

      def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] = {
        val runnable = new PromiseCompletingRunnable(body)
        executor.prepare.execute(runnable)
        runnable.promise.future
      }
    

    特别是,它创建了一个Promise.DefaultPromisewhich implements onComplete。在同一个源文件中,您还可以看到默认的Promise 实现也是Future。当我们调用promise.future 时,它只是将自身返回为Future。所以它都在标准库中。

    如果你去search the Scala repository for "def onComplete",你只会得到几个结果,所以很容易找到。

    【讨论】:

      【解决方案2】:

      Futuretrait,这意味着它不必有实现;它可以保留抽象以由其他东西实现。在这种情况下,您可能最终会得到某种形式的Promise

      def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = {
            val preparedEC = executor.prepare()
            val runnable = new CallbackRunnable[T](preparedEC, func)
            dispatchOrAddCallback(runnable)
          }
      

      【讨论】:

        猜你喜欢
        • 2011-05-30
        • 2015-02-10
        • 1970-01-01
        • 2015-05-16
        • 2019-04-20
        • 2012-04-29
        • 2017-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多