Akka Streams源流上的mapConcat运算符

spa*_*rkr 4 scala akka-stream

我正在阅读Akka流的文档,我遇到了mapConcat运算符,就像flatMap一样(至少在概念层面).

这是一个简单的例子:

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)))
Run Code Online (Sandbox Code Playgroud)

我期待源的类型是:

akka.stream.scaladsl.Source[Future[scala.collection.immutable.Range.Inclusive],akka.NotUsed]
Run Code Online (Sandbox Code Playgroud)

为什么不是这样?

我对每行的类型的理解如下所示:

Source
  .fromFuture(Future.successful(1 to 10)) // Source[Future[Int]]
  .mapConcat(identity) // Source[Int]
  .runForeach(println)
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*ian 6

签名Source.fromFuture是:

def fromFuture[O](future: Future[O]): Source[O, NotUsed]
Run Code Online (Sandbox Code Playgroud)

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

Source[scala.collection.immutable.Range.Inclusive, NotUsed]
Run Code Online (Sandbox Code Playgroud)

Scala 文档

下面是一个例子演示之间的差mapmapConcat:

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)
Run Code Online (Sandbox Code Playgroud)