概述
本篇文章分享Mono.just与Mono.defer的区别并用代码进行了测试。
Mono.just
JDK注释
Create a new Mono that emits the specified item, which is captured at instantiation time.
翻译
在实例化时创建mono并发出元素。
图示

Mono.defer
JDK注释
Create a Mono provider that will supply a target Mono to subscribe to for each Subscriber downstream.
翻译
创建一个Mono 提供者,为下游的每一个订阅者提供订阅目标。
图示

代码测试
public static void main(String[] args) throws Exception{
Mono just = Mono.just(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
Mono defer = Mono.defer(()->{
return Mono.just(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
});
just.subscribe(System.out::println);
defer.subscribe(System.out::println);
Thread.sleep(2000);
just.subscribe(System.out::println);
defer.subscribe(System.out::println);
}
输出。

总结
just发出的元素是在实例化时就准备好的
defer在有订阅时才发出元素。


本文探讨了Reactor库中Mono.just和Mono.defer的区别。Mono.just在创建时即确定发出的值,而Mono.defer则在订阅时才根据提供的函数生成值。通过代码测试展示了当有多个订阅者时,defer能确保每个订阅者接收到的是订阅时刻的状态。
685

被折叠的 条评论
为什么被折叠?



