You can view the flow with the 2 sinks as being a sink in itself. To construct more complicated Graph's we can use the functions provided in GraphDSL.
Consider, in a generic case
def splittingSink[T, M1, M2, Mat](f: T ⇒ Option[T], someSink: Sink[T, M1], noneSink: Sink[None.type, M2], combineMat: (M1, M2) ⇒ Mat): Sink[T, Mat] = {
val graph = GraphDSL.create(someSink, noneSink)(combineMat) { implicit builder ⇒
(sink1, sink2) ⇒ {
import GraphDSL.Implicits._
//Here we broadcast the Some[T] values to 2 flows,
// each filtering to the correct type for each sink
val bcast = builder.add(Broadcast[Option[T]](2))
bcast.out(0) ~> Flow[Option[T]].collect { case Some(t) ⇒ t } ~> sink1.in
bcast.out(1) ~> Flow[Option[T]].collect { case None ⇒ None } ~> sink2.in
//The flow that maps T => Some[T]
val mapper = builder.add(Flow.fromFunction(f))
mapper.out ~> bcast.in
//The whole thing is a Sink[T]
SinkShape(mapper.in)
}
}
Sink.fromGraph(graph)
}
This returns a Sink[T,Mat]
that, using the provided function, will map the incoming T
elements into an Option[T]
, which is then directed to one of the provided sinks.
An example of the usage:
val sink = splittingSink(
(s: String) ⇒ if (s.length % 2 == 0) Some(s) else None,
Sink.foreach[String](s),
Sink.foreach[None.type](_ ⇒ println("None")),
(f1: Future[_], f2: Future[_]) ⇒ Future.sequence(Seq(f1, f2)).map(_ ⇒ Done)
)
Source(List("One", "Two", "Three", "Four", "Five", "Six"))
.runWith(sink)
.onComplete(_ ⇒ println("----\nDone"))
Output:
None
None
None
Four
Five
None
----
Done
Usage of GraphDSL are discussed further in the documentation section about Stream Graphs.