在reactor中有一种方法可以等待特定数量的订阅者,然后发布者才能开始发布。
我想实现一个稍微不同的场景:
如果等待的周期持续时间太长(比时间t2长),则发布者无论如何都会开始发光。
怎么做?
答案 0 :(得分:1)
没有可以执行此操作的操作员,但您应该能够使用标准AtomicInteger
- publish()
周期使用计划任务和connect()
模拟该操作:
@Test
public void deferredConnect() throws InterruptedException {
ConnectableFlux<Integer> connectableFlux = Flux.range(1, 10)
.publish();
AtomicInteger subCount = new AtomicInteger();
Flux<Integer> deferredConnect = connectableFlux
.doOnSubscribe(sub -> {
int current = subCount.incrementAndGet();
Schedulers.parallel().schedule(() -> {
if (subCount.compareAndSet(current, -1)) {
connectableFlux.connect();
}
}, 1, TimeUnit.SECONDS);
});
deferredConnect.subscribe(v -> System.out.println("1: " + v));
Thread.sleep(500);
deferredConnect.subscribe(v -> System.out.println("2: " + v));
Thread.sleep(400);
deferredConnect.subscribe(v -> System.out.println("3: " + v));
Thread.sleep(200);
assertThat(subCount).hasNonNegativeValue();
Thread.sleep(800);
assertThat(subCount).hasNegativeValue();
}