【问题标题】:How to flatten a Flow[T, Seq[Seq[String]], NotUsed] into a Flow[T, Seq[String], NotUsed]如何将 Flow[T, Seq[Seq[String]], NotUsed] 展平为 Flow[T, Seq[String], NotUsed]
【发布时间】:2018-09-20 01:07:30
【问题描述】:

我有一个 Flow[T, Seq[Seq[String]], NotUsed] 类型的流。

我想以示例流的方式将其展平

ev1: Seq(Seq("a", "b"), Seq("n", "m")
ev2: Seq(Seq("x", "y"))

应该变成如下流:

ev1: Seq("a", "b")
ev2: Seq("n", "m")
ev3: Seq("x", "y")

【问题讨论】:

    标签: akka-stream


    【解决方案1】:

    使用mapConcat(identity):

      implicit val actorSystem = ActorSystem()
      implicit val materializer = ActorMaterializer()
    
      val events = Vector(
        Vector(Vector(1, 2), Vector(3, 4)),
        Vector(Vector(5, 6))
      )
    
      Source.apply(events)
        .mapConcat(identity)
        .runForeach(println)
    
      actorSystem.terminate()
    

    打印

    Vector(1, 2)
    Vector(3, 4)
    Vector(5, 6)
    

    一般来说,使用mapConcat,您可以将事件序列展平为主流。

    【讨论】:

    • 但仍然想知道为什么这不适用于 Seq,仅适用于 Vector
    • @spaudanjo 它不起作用scala.Seq,即scala.collection.Seq,因为类型不匹配。 Source.apply 要求它的参数是scala.collection.immutable.Iterable,当然scala.collection.Seq 不能保证是不可变的,它不是scala.collection.immutable.Iterable 的子类型,而Vector 实际上是不可变的。例如,它也适用于List;只是我平时到处默认使用Vector
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多