Akka Streams:如何从GraphDSL API获得Materialized Sink输出?

cla*_*lay 4 scala akka-stream

这是使用GraphDSL API的一个非常简单的新手问题.我读了几个相关的SO线程,我没有看到答案:

val actorSystem = ActorSystem("QuickStart")
val executor = actorSystem.dispatcher
val materializer = ActorMaterializer()(actorSystem)

val source: Source[Int, NotUsed] = Source(1 to 5)
val throttledSource = source.throttle(1, 1.second, 1, ThrottleMode.shaping)
val intDoublerFlow = Flow.fromFunction[Int, Int](i => i * 2)
val sink = Sink.foreach(println)

val graphModel = GraphDSL.create() { implicit b =>
  import GraphDSL.Implicits._

  throttledSource ~> intDoublerFlow ~> sink

  // I presume I want to change this shape to something else
  // but I can't figure out what it is.
  ClosedShape
}
// TODO: This is RunnableGraph[NotUsed], I want RunnableGraph[Future[Done]] that gives the
// materialized Future[Done] from the sink. I presume I need to use a GraphDSL SourceShape
// but I can't get that working.
val graph = RunnableGraph.fromGraph(graphModel)

// This works and gives me the materialized sink output using the simpler API.
// But I want to use the GraphDSL so that I can add branches or junctures.
val graphThatIWantFromDslAPI = throttledSource.toMat(sink)(Keep.right)
Run Code Online (Sandbox Code Playgroud)

Ste*_*tti 13

诀窍是将你希望物化值(在你的情况下sink)的阶段传递给GraphDSL.create.作为第二个参数传递的函数也会发生变化,需要Shape输入参数(s在下面的示例中),您可以在图形中使用该参数.

  val graphModel: Graph[ClosedShape, Future[Done]] = GraphDSL.create(sink) { implicit b => s =>
    import GraphDSL.Implicits._

    throttledSource ~> intDoublerFlow ~> s

    // ClosedShape is just fine - it is always the shape of a RunnableGraph
    ClosedShape
  }
  val graph: RunnableGraph[Future[Done]] = RunnableGraph.fromGraph(graphModel)
Run Code Online (Sandbox Code Playgroud)

更多信息可以在文档中找到.


Mar*_*ler 6

val graphModel = GraphDSL.create(sink) { implicit b: Builder[Future[Done]] => sink =>
  import akka.stream.scaladsl.GraphDSL.Implicits._

  throttledSource ~> intDoublerFlow ~> sink

  ClosedShape
}
val graph: RunnableGraph[Future[Done]] = RunnableGraph.fromGraph(graphModel)    
val graphThatIWantFromDslAPI: RunnableGraph[Future[Done]] = throttledSource.toMat(sink)(Keep.right)
Run Code Online (Sandbox Code Playgroud)

GraphDSL API的问题在于隐式Builder严重超载.你需要用你的水槽create,从而关Builder[NotUsed]Builder[Future[Done]]现在代表一个功能builder => sink => shape,而不是builder => shape.