flux2
1.publish
生成的是connectableFlux,connectableFlux发出从connect到disconnect之间的数据,当对象销毁时也会自动disconnect
ConnectableFlux<LocalDateTime> flux = Flux.interval(Duration.ofMillis(1)).map(seq-> LocalDateTime.now()) .publish(1); flux.subscribe(s->{ System.out.println(s + "55555555"); }); flux.connect(); Thread.sleep(100); flux.subscribe(s->{ System.out.println(s + "111111111"); }); flux.subscribe(s->{ System.out.println(s + "222222222"); }); Thread.sleep(100); flux.disconnect();
上述代码进行了三次subscribe,每个subscribe都会收到 max(subscribe时间,connect时间)到disconnect时间的数据,
publish还有一个参数,表示connect之后提前先跳过x调数据之后开始emit
2.replay
生成的是connectableFlux,emit从connect到disconnect之间的数据,不论什么时候subscribe
final AtomicInteger i = new AtomicInteger(0); final AtomicInteger j = new AtomicInteger(0); ConnectableFlux<String> flux = Flux.interval(Duration.ofMillis(1)).map(seq-> LocalDateTime.now()).map(s->{ System.out.println(i.getAndIncrement()); return s.toString(); }).replay(); flux.subscribe(s->System.out.println(j.getAndIncrement())); flux.connect(); Thread.sleep(100);
连词打印的结果完全一致
3.autoConnect形式,
表示connectableFlux不需要connect
Flux<LocalDateTime> flux2 = Flux.interval(Duration.ofMillis(1)).map(seq-> LocalDateTime.now()).publish().autoConnect(2); flux2.subscribe(s->System.out.println(j.getAndIncrement())); flux2.subscribe(s->System.out.println(j.getAndIncrement()));
autoConnect的参数表示subscribe多少次后开始emit数据