如何从广播的Akka流中获取订阅者和发布者?

时间:2015-07-02 21:51:42

标签: scala akka-stream reactive-streams

在使用更复杂的图表时,我遇到了将流程图和订阅者从流程中删除的问题。我的目标是提供发布者和订阅者的API,并在内部运行Akka流媒体。这是我的第一次尝试,效果很好。

val subscriberSource = Source.subscriber[Boolean]
val someFunctionSink = Sink.foreach(Console.println)

val flow = subscriberSource.to(someFunctionSink)

//create Reactive Streams Subscriber
val subscriber: Subscriber[Boolean] = flow.run()

//prints true
Source.single(true).to(Sink(subscriber)).run()

但是随后使用更复杂的广播图,我不确定如何获取Subscriber和Publisher对象?我需要部分图表吗?

val subscriberSource = Source.subscriber[Boolean]
val someFunctionSink = Sink.foreach(Console.println)
val publisherSink = Sink.publisher[Boolean]

FlowGraph.closed() { implicit builder =>
  import FlowGraph.Implicits._

  val broadcast = builder.add(Broadcast[Boolean](2))

  subscriberSource ~> broadcast.in
  broadcast.out(0) ~> someFunctionSink
  broadcast.out(1) ~> publisherSink
}.run()

val subscriber: Subscriber[Boolean] = ???
val publisher: Publisher[Boolean] = ???

1 个答案:

答案 0 :(得分:7)

当您调用RunnableGraph.run()时,将运行该流,结果是该运行的“具体化值”。

在您的简单示例中,Source.subscriber[Boolean]的具体化值为Subscriber[Boolean]。在您的复杂示例中,您希望将图表的多个组件的具体化值组合为元组(Subscriber[Boolean], Publisher[Boolean])的具体化值。

您可以通过将您感兴趣的组件的物化值传递给FlowGraph.closed(),然后指定一个函数来组合物化值:

import akka.stream.scaladsl._
import org.reactivestreams._

val subscriberSource = Source.subscriber[Boolean]
val someFunctionSink = Sink.foreach(Console.println)
val publisherSink = Sink.publisher[Boolean]

val graph =
  FlowGraph.closed(subscriberSource, publisherSink)(Keep.both) { implicit builder ⇒
    (in, out) ⇒
      import FlowGraph.Implicits._

      val broadcast = builder.add(Broadcast[Boolean](2))

      in ~> broadcast.in
      broadcast.out(0) ~> someFunctionSink
      broadcast.out(1) ~> out
  }
val (subscriber: Subscriber[Boolean], publisher: Publisher[Boolean]) = graph.run()

请参阅Scaladocs for more information about the overloads of FlowGraph.closed

Keep.both是函数(a, b) => (a, b)

的缩写