我想围绕Pubsub主题构建一个流程
\-----------------------------------------------------\
\ ------------------ ------------ ------------- \
> > wrapWithPublish > > toPubsub | | fromPubsub > >
/ ------------------ ------------ ------------- /
/-----------------------------------------------------/
这是我到目前为止编写的代码
def mediatorFlow[In, Out](mediator: ActorRef, topic: String): Flow[In, Out, Unit] = {
val source =
Source
.actorRef[Out](10, OverflowStrategy.dropHead)
.mapMaterializedValue { ref => mediator ! DistributedPubSubMediator.Subscribe(topic, ref); ref }
val wrapWithPublish =
Flow[In].map(DistributedPubSubMediator.Publish(topic, _))
val unsubscribe = DistributedPubSubMediator.Unsubscribe(topic, ref???)
val toPubsub =
Sink.actorRef[DistributedPubSubMediator.Publish](mediator, unsubscribe)
Flow.fromSinkAndSource(wrapWithPublish to toPubsub, source)
}
问题在于unsubscribe
的定义,我想在流的末尾发送一个DistributedPubSubMediator.Subscribe
,它指定ref
应该是{{的具体化值1}}定义如上。
我知道Pubsub会在流结束时自动取消订阅Actor。但我很好奇如何解决这个问题。
答案 0 :(得分:3)
要实现这一点,您需要构建一个比fromSinkAndSource
更紧密的Flow,您将需要使用GraphDSL:
val source = ... // as above
Flow.fromGraph(GraphDSL.create(source) { implicit b =>
src =>
import GraphDSL.Implicits._
val concat = b.add(Concat[Any](2))
val wrapWithPublish = b.add(Flow[In].map(DistributedPubSubMediator.Publish(topic, _)))
val toPubSub = b.add(Sink.actorRef[Any](mediator, unsubscribe))
wrapWithPublish ~> concat ~> toPubSub
b.materializedValue.map(DistributedPubSubMediator.Unsubscribe(topic, _)) ~> concat
FlowShape(wrapWithPublish.in, src.out)
})
通过这种方式,您可以将其中一个部分的具体化值注入流元素的级别,使其可以被发送到pubsub中介。