Akka Streams - 如何在图形中保持辅助接收器的物化值

时间:2016-10-21 18:25:44

标签: scala akka akka-stream

我有一个返回Flow的函数,其逻辑涉及将图的一些元素传递给作为参数传递的辅助Sink。我希望保留辅助Sink的具体化值,以便在构建的流启动时能够对其值进行操作。

这是我正在建设的流程的粗略画面:

IN ~> (logic: In => Out) ~> Broadcast ~> AuxFilter ~> AuxSink
                                      ~> OutFilter ~> OUT

示例代码:

case class Incoming()
trait Element
case class Outcoming() extends Element
case class Persistent() extends Element

def flow[Mat](auxSink: Sink[Persistent, Mat]): Flow[Incoming, Outcoming, NotUsed] = {
  val isPersistent = Flow[Element].collect {
    case persistent: Persistent => persistent
  }

  val isRunning = Flow[Element].collect {
    case out: Outcoming => out
  }

  val magicFlow: Flow[Incoming, Element, NotUsed] = Flow[Incoming]
    .map(_ => if (Random.nextBoolean()) Outcoming() else Persistent())

  Flow.fromGraph {
    GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      val magic = b.add(magicFlow)
      val bcast = b.add(Broadcast[Element](2))
      val sink = b.add(isRunning)

                   bcast.out(0) ~> isPersistent ~> auxSink
      magic.out ~> bcast.in
                   bcast.out(1) ~> isRunning ~> sink.in

      FlowShape(magic.in, sink.out)
    }
  }
}

有没有办法以某种方式将auxSink' Mat传递给结果Flow

感谢。

1 个答案:

答案 0 :(得分:7)

回答我自己的问题......

发现它! Flow.alsoToMat的来源完全指出了我需要的逻辑 - 访问辅助图的具体化值(在我的情况下为auxSink),必须将其形状导入到通过传递构造的图中它作为GraphDSL.create()的参数。

def flow[Mat](auxSink: Sink[Persistent, Mat]): Flow[Incoming, Outcoming, Mat] = {
  val isPersistent = ...
  val isRunning = ...
  val magicFlow = ...

  Flow.fromGraph {
    GraphDSL.create(auxSink) { implicit b => aux =>
      import GraphDSL.Implicits._

      val magic = b.add(magicFlow)
      val bcast = b.add(Broadcast[Element](2))
      val sink = b.add(isRunning)

      magic ~> bcast ~> isPersistent ~> aux
               bcast ~> isRunning ~> sink

      FlowShape(magic.in, sink.out)
    }
  }
}