Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the type parameters to Source<Out,Mat> mean?

I'm trying to understand the Source type for Akka streams, specified here.

Unfortunately, the documentation and examples I've found don't explain what each of the type parameters actually mean. I'm guessing that Out is the type that the source emits when materialized. Is that correct? What is the other type parameter Mat ?

like image 325
Erix Avatar asked Dec 13 '16 19:12

Erix


1 Answers

Out

You are correct, this is the type of the elements which are emitted by the Source.

Mat

It is the type of the Source's materialisation. Note that every stage (Flows, Sinks, etc.) will materialise to a value as well. This is essentially a byproduct of the stage itself after it is run.

You can picture it as a mean of interacting with the stage while it's running. Looking at examples of ready-made Sources offered by Akka is a good way of getting the gist of it.

  • Source.single will materialise to NotUsed. You got no mean of interacting with the source, as it will produce only one element straightaway and then complete.

  • Source.queue will materialise to a SourceQueue. This is a more interesting case, as you can interact with the source by offering messages to it. The messages you offer will be emitted by the source.

  • Source.maybe will materialise to a Promise. You can use the Promise to control the source and make it emit one element, or None.

When you concatenate different stages, note that every stage can potentially have a useful materialized value. You get to choose which ones to keep by using viaMat/toMat and Keep DSL. One or more materialized values will be returned when run() is called on the composed graph.

Taking a look at the types in the examples below is the best way to get the gist of the API:

  val source: Source[Int, MatSrc]
  val sink: Sink[Int, MatSnk]

  val matSrc: MatSrc = source.toMat(sink)(Keep.left).run()
  val matSnk: MatSnk = source.toMat(sink)(Keep.right).run()
  val (m1: MatSrc, m2: MatSnk) = source.toMat(sink)(Keep.both).run()
  val n: NotUsed = source.toMat(sink)(Keep.none).run()

Note that the more succinct DSL which you can find in many example is actually a shortcut for the above, where only the materialized value of the last stage (e.g. the sink) is kept.

  val mat3: Mat3 = source.viaMat(flow)(Keep.right).toMat(sink)(Keep.right).run()

is the same as

  val mat3: Mat3 = source.via(flow).runWith(sink)

See the docs below for further reading.

http://doc.akka.io/docs/akka/2.4/java/stream/stream-quickstart.html#Materialized_values

like image 117
Stefano Bonetti Avatar answered Oct 17 '22 09:10

Stefano Bonetti