【问题标题】:Scala Akka Streams Merging Filter And MapScala Akka Streams 合并过滤器和映射
【发布时间】:2016-07-22 19:03:34
【问题描述】:

我想知道是否有任何方法可以优化以下 Scala 代码,因为它看起来效率不高。 基本上,我只想从流中删除任何不是Tweet 的对象并将其映射到Tweet 而不是Any

val tweetsFlow = Flow[Any].filter({
  case _: Tweet => true
  case _ => false
}).map({
  case tweet: Tweet => tweet
})

【问题讨论】:

    标签: scala akka akka-stream


    【解决方案1】:

    你可能会使用collect方法,有些像这样

    val tws = Vector(
      "foo",
      Tweet(Author("foo"), tms, "foo #akka bar"),
      1000L,
      Tweet(Author("bar"), tms, "foo #spray bar"),
      Tweet(Author("baz"), tms, "foo bar"),
      1
    )
    
    val tflow = Flow[Any].collect {
      case x: Tweet => x
    }
    Source(tws).via(tflow)
    

    【讨论】:

      【解决方案2】:

      由于您只对特定类型的过滤感兴趣,您可以使用collectType

      // case class Tweet(title: String)
      // val mixedSource: Source[Any, NotUsed] = Source(List(Tweet("1"), 3, Tweet("2")))
      val tweetsSource: Source[Tweet, NotUsed] = mixedSource.collectType[Tweet]
      // tweetsSource.runForeach(println)
      // Tweet("1")
      // Tweet("2")
      

      【讨论】:

        猜你喜欢
        • 2021-08-07
        • 2015-11-20
        • 1970-01-01
        • 2018-01-01
        • 2018-10-24
        • 2014-09-21
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        相关资源
        最近更新 更多