Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Akka Streams Merging Filter And Map

I wonder if there is any way to optimize the following Scala code because it doesn't look very efficient. Basically, I just want to remove any object which is not a Tweet from the flow and map it to Tweet instead of Any.

val tweetsFlow = Flow[Any].filter({
  case _: Tweet => true
  case _ => false
}).map({
  case tweet: Tweet => tweet
})
like image 391
idoshamun Avatar asked Oct 21 '25 11:10

idoshamun


2 Answers

You might use collect method, some like this

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)
like image 53
mike Avatar answered Oct 23 '25 01:10

mike


Since you're only interested in filtering on a specific type you can use 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")
like image 36
Xavier Guihot Avatar answered Oct 23 '25 01:10

Xavier Guihot