【问题标题】:Understanding Scala Future andThen理解 Scala 的未来
【发布时间】:2017-07-11 17:31:20
【问题描述】:

我正在尝试使用andThen 方法来注册未来的行动阶段。像这样:

implicit val executionContext = ExecutionContext.global

val f = Future(0)
f.andThen {
  case r => println(r.get + "1")
} andThen {
  case r => println(r.get + "2")
}

由于此方法异步执行并且不会产生 返回值,任何抛出的非致命异常都会报告给 执行上下文。

异步是什么意思?这意味着与未来执行本身异步吗?

【问题讨论】:

    标签: scala future


    【解决方案1】:

    异步是什么意思?这意味着异步到 未来的执行本身?

    这意味着andThen的执行将在原始Future[T]完成后发生在ExecutionContext提供的给定线程上。

    如果我们看一下实现:

    def andThen[U](pf: PartialFunction[Try[T], U])(implicit executor: ExecutionContext): Future[T] = {
      val p = Promise[T]()
      onComplete {
        case r => try pf.applyOrElse[Try[T], Any](r, Predef.conforms[Try[T]]) finally p complete r
      }
      p.future
    }
    

    此方法是Future.onComplete 的智能包装器,它是返回Unit 的副作用方法。它应用给定的函数,并返回原始的Future[T] 结果。正如文档所述,当您想要保证将来注册的多个 onComplete 回调的顺序时,它很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2015-11-24
      • 1970-01-01
      • 2019-04-07
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多