gpt4 book ai didi

scala - 源流上的 Akka Streams mapConcat 运算符

转载 作者:行者123 更新时间:2023-12-05 00:13:51 25 4
gpt4 key购买 nike

我正在阅读 Akka 流的文档,并且遇到了类似于 flatMap 的 mapConcat 运算符(至少在概念级别上)。

这是一个简单的例子:

scala> val src = Source.fromFuture(Future.successful(1 to 10))
src: akka.stream.scaladsl.Source[scala.collection.immutable.Range.Inclusive,akka.NotUsed] = Source(SourceShape(FutureSource.out(51943878)))

我期待那种类型的 Source 是:
akka.stream.scaladsl.Source[Future[scala.collection.immutable.Range.Inclusive],akka.NotUsed]

为什么不是这样?

我对每一行类型的理解如下图:
Source
.fromFuture(Future.successful(1 to 10)) // Source[Future[Int]]
.mapConcat(identity) // Source[Int]
.runForeach(println)

但是上面例子中的 Source 类型并不是我想的那样!

最佳答案

签名Source.fromFuture是:

def fromFuture[O](future: Future[O]): Source[O, NotUsed]

在您的示例中 O类型为 scala.collection.immutable.Range.Inclusive因此返回类型为 Source.fromFuture是:
Source[scala.collection.immutable.Range.Inclusive, NotUsed]

斯卡拉 docs

这是一个演示 map 之间差异的示例和 mapConcat :
def f: Future[List[Int]] = Future.successful((1 to 5).toList)

def g(l: List[Int]): List[String] = l.map(_.toString * 2)

Source
.fromFuture(f)
.mapConcat(g) // emits 5 elements of type Int
.runForeach(println)

Source
.fromFuture(f)
.map(g) // emits one element of type List[Int]
.runForeach(println)

关于scala - 源流上的 Akka Streams mapConcat 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48098370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com