简体   繁体   English

Akka流:在流启动时执行操作

[英]Akka-streams: execute action on flow start

Having a flow description in akka-streams akka流中具有流描述

val flow: Flow[Input, Output, Unit] = ???

, how do I modify it to get a new flow description that performs a specified side-affect on start, ie when flow is materialized? ,如何修改它以获得一个新的流描述,该描述在开始时即流实现时执行指定的副作用?

Starting materialization of a stream processing graph will set it in motion piece by piece, concurrently. 流处理图的开始实现将同时将其逐个设置在运动中。 The only way to perform an action that is guaranteed to happen before the first element is passed somewhere within that graph is to perform that action before materializing the graph. 确保将第一个元素传递到该图内某个位置之前发生的操作的唯一方法是在实例化该图之前执行该操作。 In this sense the answer by sschaef is slightly incorrect: using mapMaterializedValue runs the action pretty early, but not such that it is guaranteed to happend before the first element is processed. 从这个意义上说,sschaef的回答有点不正确:使用mapMaterializedValue可以mapMaterializedValue运行该动作,但不能保证在处理第一个元素之前就发生了该动作。

If we are talking about a Flow here which only takes in inputs on one side and produces outputs on the other—ie it does not contain internal cycles or data sources—then one thing you can do to perform an action before the first element arrives is to attach a processing step to its input that does that: 如果我们在这里讨论的Flow仅在一侧接受输入而在另一侧产生输出(即,它不包含内部循环或数据源),那么您可以做的一件事情是在第一个元素到达之前执行操作在其输入上附加一个处理步骤,以执行以下操作:

def effectSource[T](block: => Unit) = Source.fromIterator(() => {block; Iterator.empty})
val newFlow = Flow[Input].prepend(effectSource(/* do stuff */)).via(flow)

Note 注意

The above is using upcoming 2.0 syntax, in Akka Streams 1.0 it would be Source(() => { block; Iterator.empty }) and the prepend operation would need to be done using the FlowGraph DSL (the graph can be found here ). 上面使用的是即将到来的2.0语法,在Akka Streams 1.0中,它将是Source(() => { block; Iterator.empty })并且需要使用FlowGraph DSL进行前置操作(可以在此处找到该图) 。

您自己说了,使用实现的力量:

val newFlow = flow.mapMaterializedValue(_ ⇒ println("materialized"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM