简体   繁体   English

Akka Streams源流上的mapConcat运算符

[英]Akka Streams mapConcat Operator on Source Streams

I'm reading through the documentation for Akka streams and I came across the mapConcat operator which is like the flatMap (at least on the conceptual level). 我正在阅读Akka流的文档,我遇到了mapConcat运算符,就像flatMap一样(至少在概念层面)。

Here is a simple example: 这是一个简单的例子:

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)))

I was expecting that type of the Source is rather: 我期待源的类型是:

akka.stream.scaladsl.Source[Future[scala.collection.immutable.Range.Inclusive],akka.NotUsed]

Why is that not the case? 为什么不是这样?

My understanding of the types for each line is as shown below: 我对每行的类型的理解如下所示:

Source
  .fromFuture(Future.successful(1 to 10)) // Source[Future[Int]]
  .mapConcat(identity) // Source[Int]
  .runForeach(println)

But the Source type in the example above is not what I thought it was! 但上面例子中的Source类型并不是我想象的那样!

The signature of Source.fromFuture is: Source.fromFuture的签名是:

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

In your example O is of type scala.collection.immutable.Range.Inclusive and therefore the return type of Source.fromFuture is: 在您的示例中, O的类型为scala.collection.immutable.Range.Inclusive ,因此Source.fromFuture的返回类型为:

Source[scala.collection.immutable.Range.Inclusive, NotUsed]

Scala docs Scala 文档

Here is an example demonstrating the difference between map and mapConcat : 这是一个演示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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM