Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 使用具有两个接收器的源并获得一个接收器的结果_Scala_Akka_Akka Stream - Fatal编程技术网

Scala 使用具有两个接收器的源并获得一个接收器的结果

Scala 使用具有两个接收器的源并获得一个接收器的结果,scala,akka,akka-stream,Scala,Akka,Akka Stream,我想使用一个具有两个不同接收器的源 简化示例: val source = Source(1 to 20) val addSink = Sink.fold[Int, Int](0)(_ + _) val subtractSink = Sink.fold[Int, Int](0)(_ - _) val graph = GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ val bcast = bu

我想使用一个具有两个不同接收器的源

简化示例:

val source = Source(1 to 20)

val addSink = Sink.fold[Int, Int](0)(_ + _)
val subtractSink = Sink.fold[Int, Int](0)(_ - _)

val graph = GraphDSL.create() { implicit builder =>
  import GraphDSL.Implicits._

  val bcast = builder.add(Broadcast[Int](2))

  source ~> bcast.in

  bcast.out(0) ~> addSink
  bcast.out(1) ~> subtrackSink

  ClosedShape
}

RunnableGraph.fromGraph(graph).run()

val result: Future[Int] = ???
我需要能够检索addSink的结果。RunnableGraph.fromGraphgraph.run给我的是NotUsed,
但是我想得到第一次折叠下沉的结果。有可能吗?

将两个接收器传递给graph builder的create方法,该方法允许您访问它们各自的物化值:

val graph = GraphDSL.create(addSink, subtractSink)((_, _)) { implicit builder =>
  (aSink, sSink) =>
  import GraphDSL.Implicits._

  val bcast = builder.add(Broadcast[Int](2))

  source ~> bcast.in
  bcast.out(0) ~> aSink
  bcast.out(1) ~> sSink
  ClosedShape
}

val (addResult, subtractResult): (Future[Int], Future[Int]) =
  RunnableGraph.fromGraph(graph).run() 
或者,您可以放弃graph DSL并使用:

上面给出了addSink的具体化值。如果要同时获取addSink和subtractSink的物化值,请使用Keep.both:

val result: Future[Int] =
  Source(1 to 20)
    .alsoToMat(addSink)(Keep.right)
    .toMat(subtractSink)(Keep.left)
    .run()
val (addResult, subtractResult): (Future[Int], Future[Int]) =
  Source(1 to 20)
    .alsoToMat(addSink)(Keep.right)
    .toMat(subtractSink)(Keep.both) // <--
    .run()