What does Keep in akka stream mean?

纵然是瞬间 提交于 2020-07-08 10:32:14

问题


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?


回答1:


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.




回答2:


Keep.left keeps only the left (first) of the input values. Keep.right only keeps the right (second) of two input values.




回答3:


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.



来源:https://stackoverflow.com/questions/47116358/what-does-keep-in-akka-stream-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!