Reputation: 34099
I am learning akka stream and encounter Keep.left and Keep.right in the code:
implicit val system = ActorSystem("KafkaProducer")
implicit val materializer = ActorMaterializer()
val source = Source(List("a", "b", "c"))
val sink = Sink.fold[String, String]("")(_ + _)
val runnable: RunnableGraph[Future[String]] = source.toMat(sink)(Keep.right)
val result: Future[String] = runnable.run()
What does here Keep.right mean?
Upvotes: 6
Views: 3285
Reputation: 51
Because jvm does type erasure, Akka does not care about the type between Source Flow Sink when designing Stream, but Source Flow Sink is a typed class. In order for the type to pass between the components, you need to attach a description value, which is the meaning of Keep. By default, the message type in the final result is consistent with the leftmost Source , Keep.left(). You can also set it to something else like Keep.right().
Strictly speaking, Keep specifies the value type, not the value. enter link description here
val r3: RunnableGraph[Future[Int]] = source.via(flow).toMat(sink)(Keep.right)
Change "Keep.right" to "Keep left":
val r3: RunnableGraph[Future[Int]] = source.via(flow).toMat(sink)(Keep.left)
Will get "type mismatch " error.
Upvotes: 0
Reputation: 22449
Every stream processing stage can produce a materialized value which can be captured using viaMat
or toMat
(as opposed to via()
or to()
, respectively). In your code snippet, the using of source.toMat(sink)
indicates that you're interested in capturing the materialized value of the source and sink and Keep.right
keeps the right side (i.e. sink) of the materialized value. Keep.left
would keep the materialized value on the left side (i.e. source), and Keep.both
would allow you to keep both.
More details is available in relevant sections in the Akka Streams documentation.
Upvotes: 8
Reputation: 16945
Keep.left
keeps only the left (first) of the input values. Keep.right
only keeps the right (second) of two input values.
Upvotes: 1