Via/ViaMat/to/toMat in Akka Stream

前端 未结 1 870
走了就别回头了
走了就别回头了 2021-01-30 23:14

Can someone explain clearly what are the difference between those 4 methods ? When is it more appropriate to use each one ? Also generally speaking what is the name of this Grou

相关标签:
1条回答
  • 2021-01-30 23:36

    All these methods are necessary to join two streams into one stream. For example, you can create a Source out of a Source and a Flow, or you can create a Sink out of a Flow and a Sink, or you can create a Flow out of two Flows.

    For this, there are two basic operations, to and via. The former allows one to connect either a Source or a Flow to a Sink, while the latter allows to connect a Source or a Flow to a Flow:

    source.to(sink)   ->  runnable graph
    flow.to(sink)     ->  sink
    
    source.via(flow)  ->  source
    flow1.via(flow2)  ->  flow
    

    For the reference, a runnable graph is a fully connected reactive stream which is ready to be materialized and executed.

    *Mat versions of various operations allow one to specify how materialized values of streams included in the operation should be combined. As you may know, each stream has a materialized value which can be obtained when the stream is materialized. For example, Source.queue yields a queue object which can be used by another part of your program to emit elements into the running stream.

    By default to and via on sources and flows only keeps the materialized value of the stream it is called on, ignoring the materialized value of its argument:

    source.to(sink)    yields   mat.value of source
    source.via(flow)   yields   mat.value of source
    
    flow.to(sink)      yields   mat.value of flow
    flow1.via(flow2)   yields   mat.value of flow1
    

    Sometimes, however, you need to keep both materialized values or to combined them somehow. That's when Mat variants of methods are needed. They allow you to specify the combining function which takes materialized values of both operands and returns a materialized value of the combined stream:

    source.to(sink)    equivalent to   source.toMat(sink)(Keep.left)
    flow1.via(flow2)   equivalent to   flow1.viaMat(flow2)(Keep.left)
    

    For example, to keep both materialized values, you can use Keep.both method, or if you only need the mat.value of the "right" operand, you can use Keep.right method:

    source.toMat(sink)(Keep.both)   yields   a tuple (mat.value of source, mat.value of sink)
    
    0 讨论(0)
提交回复
热议问题