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
})
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With