我正在玩Akka Streams并且对通过带参数的函数构建Flow
感到好奇。应从前一个流阶段传递参数。
我们假设我们有以下输入和输出:
case class InitElement(v: Int)
trait StreamResult
case class StageA(v: Int) extends StreamResult
case class StageB(v: Int) extends StreamResult
trait StreamFailure extends StreamResult { val msg: String }
case class StageAFailure(msg: String) extends StreamFailure
case class StageBFailure(msg: String) extends StreamFailure
他们的流阶段看起来像:
val stageA = Flow[InitElement].map {
init =>
if (init.v > 10)
StageA(init.v)
else
StageAFailure(s"${init.v} less than 10")
}
def stageB(input: StreamResult)(externalService: Set[Int]) = Flow[StreamResult].map {
case failure: StreamFailure => failure
case StageA(v) =>
if (externalService.contains(v))
StageB(v)
else
StageBFailure(s"$v is absent in external service")
}
val graph = Source.single(InitElement(12))
.via(stageA)
//How can I pass output of previous stage into 'stageB' function?
.via(stageB(_)(Set(11, 15, 20)))
.toMat(Sink.head)(Keep.right)
我认为没有办法将stageA
的结果传递给构建下一阶段的函数。
我该如何实现?
答案 0 :(得分:3)
您对stageB
的定义会构建Flow[StreamResult, StreamResult, _]
。它不需要将(input: StreamResult)
作为参数。请注意,您不要在input
定义中的任何位置使用stageB
。该元素来自您Flow[StreamResult]
上的map
。
这应该足够了:
def stageB(externalService: Set[Int]) = … // As you wrote it
val graph = Source.single(InitElement(12))
.via(stageA)
.via(stageB(Set(11, 15, 20)))
.toMat(Sink.head)(Keep.right)