Actually, I think scala code in this case kinda self explaining (probably more than the java one).
If you have a Flow[A]
, and a function with A => B
, the map
what you are looking for. If you have a function with A => Future[B]
(I have no idea what is the java eq of the async wrapper), the mapAsync
what you are looking for (or even mapAsyncUnordered
if the order is don’t care). Both will return a Flow[A, B, NotUsed]
. If you have an x: Flow[A, B, NotUsed]
, you can use Flow[A].via(x)
which will also return a Flow[A, B, NotUsed]
.
For “terminating” or closing a flow/source you can use to
or toMat
(to will returns the matvalue of the upstream, and toMat will wait for a function that combines the upstream and the sink matvalues). If you have a closed graph (like Source.single(1).to(Sink.ignore )
) you can run it with run
. Until you run it, it is like a description of the computation pipeline, when you run it, it starts to generate/consume elements, and also returns with the matvalues. Most of the times we start a stream from the source (like Source.single(1).map(_ + 1)
) for a shorthand we can write runWith(sink)
instead of toMat(sink)(Keep.right).run()
this is bcs most times we are interested in the Sinks matValue.
If you use intelliJ, I would recommend to “click into” (aka ctrl/command + click) functions, and read the documentation over them. Most of the times they are pretty much explains what that thing supposed to do. Also, these tools are enable a type driven approach, if you have a function signiture, you can find the needed function that will fit.
For quick references;
(From the second link, and your second example, I think this is much better than using thenApply
.)
I know that the whole streams lib is a bit too much for beginners, but you should read the whole docs at least two times, not bcs you need to learn/understand all of it, but just to get the idea where you can search things if you get blocked. It seems like a big investment, but without a solid foundation, you will probably shoot yourself (with reinventing things that are already written probably better, or writing things noted as really dangerous (like cycles)).