代码之家  ›  专栏  ›  技术社区  ›  Alexander Arendar

Future.zip和Future.zip与实现略有不同。为什么?

  •  3
  • Alexander Arendar  · 技术社区  · 6 年前

    scala.concurrent.Future.scala :

    def zip[U](that: Future[U]): Future[(T, U)] = {
        implicit val ec = internalExecutor
        flatMap { r1 => that.map(r2 => (r1, r2)) }
      }
    
    def zipWith[U, R](that: Future[U])(f: (T, U) => R)(implicit executor: ExecutionContext): Future[R] =
        flatMap(r1 => that.map(r2 => f(r1, r2)))(internalExecutor)
    

    f zipWith 案例。我很感兴趣,为什么 internalExecutor zip 因此在两个底层 map flatMap 调用,但仅在 平面图 拉链

    据我所知,经过一番思考 f型 内部执行人 (当前线程)。这种理解正确吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Viktor Klang    6 年前

    应用 f 已完成供应 ExecutionContext internalExecutor 用于执行展平操作。规则基本上是:当用户提供逻辑时,该逻辑在 执行上下文

    你可以想象 zipWith 执行为 this.zip(that).map(f.tupled) zip 执行为 zipWith(Tuple2.apply)(internalExecutor) .