0

I would like to understand the Keep.both in akka stream but I could not find an easy on the internet.

Could someone please provide a very simple example about Keep.right and Keep.both.

I tried:

   implicit val system = ActorSystem("KafkaProducer")
    implicit val materializer = ActorMaterializer()

    val source = Source.single("Hello")_
    val sink = Sink.fold[String, String]("")(_ + _)

    val runnable: RunnableGraph[Future[String]] = source.toMat(sink)(Keep.left)
    runnable.run() 

I know, it is maybe not a good example and hopefully, someone provide a better example.

Shekhar
  • 11,438
  • 36
  • 130
  • 186
softshipper
  • 32,463
  • 51
  • 192
  • 400
  • Possible duplicate of [Via/ViaMat/to/toMat in Akka Stream](https://stackoverflow.com/questions/37911174/via-viamat-to-tomat-in-akka-stream) – Jeffrey Chung Apr 10 '19 at 19:51
  • There's a pretty good section on it in Akka Streams docs. See: https://doc.akka.io/docs/akka/current/stream/stream-composition.html#materialized-values – bszwej Apr 12 '19 at 15:43
  • It has nothing to do with Kafka Stream, you should change your title. – gabrielgiussi Apr 13 '19 at 23:21

1 Answers1

1

Simplest scenario, you need a stream to process a bunch of elements that you are going to (1) provide from outside the stream and you need to know when the (2) stream finish processing all elements.

For (1) you could use a Source.queue that is materialized into a queue and you can push elements to it via offer.

val source = Source.queue[String](100,OverflowStrategy.backpressure)

For (2) you could use a Sink.foreach that is materialized into a Future[Done] which will be completed with Success when reaching the normal end of the stream, or completed with Failure if there is a failure signaled in the stream.

val sink = Sink.foreach[String](println)

Then you need to connect source and sink and Keep.both materialized values.

val materializedValues: (SourceQueueWithComplete[String], Future[Done]) = source.toMat(sink)(Keep.both).run()
gabrielgiussi
  • 9,245
  • 7
  • 41
  • 71