我有一个处理器,可以订阅在任意时间到达的发布者。对于处理器的每个新订阅者,我想从每个发布者发出最后一个项目。
class PublishersState {
val outputProcessor = DirectProcessor.create<String>()
fun addNewPublisher(publisher: Flux<String>) {
publisher.subscribe(outputProcessor)
}
fun getAllPublishersState(): Flux<String> = outputProcessor
}
val publisher1 = Mono
.just("Item 1 publisher1")
.mergeWith(Flux.never())
val publisher2 = Flux
.just("Item 1 publisher2", "Item 2 publisher2")
.mergeWith(Flux.never())
val publishersState = PublishersState()
publishersState.getAllPublishersState().subscribe {
println("Subscriber1: $it")
}
publishersState.addNewPublisher(publisher1)
publishersState.addNewPublisher(publisher2)
publishersState.getAllPublishersState().subscribe {
println("Subscriber2: $it")
}
我需要更改上面的代码,因此它将输出以下内容:
Subscriber1: Item 1 publisher1
Subscriber1: Item 1 publisher2
Subscriber1: Item 2 publisher2
// Subscriber2 subscribers here and receives the last item from each publisher
Subscriber2: Item 1 publisher1
Subscriber2: Item 2 publisher2
是否有一种简单的方法来为每个发布者缓存最后一个项目?
答案 0 :(得分:0)
使用ReplayProcessor
代替DirectProcessor
:
val outputProcessor = ReplayProcessor.cacheLast()
答案 1 :(得分:0)
我通过以下方式解决了我的情况:
type