概述
本篇文章分享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在有订阅时才发出元素。