Mono#then 和 Mono#and 的区别?
Difference between Mono#then and Mono#and?
给定以下单声道:
Mono<Void> mono1 = Mono.fromRunnable(() -> {
System.out.println("sleep1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("mono1");
});
Mono<Void> mono2 = Mono.fromRunnable(() -> {
System.out.println("mono2");
});
Mono<Void> mono3 = Mono.fromRunnable(() -> {
System.out.println("mono3");
});
两者:
mono1
.then(mono2)
.then(mono3)
.block();
并且:
mono1
.and(mono2)
.and(mono3)
.block();
具有相同的输出:
sleep
mono1
mono2
mono3
在这种情况下 Mono#then
and Mono#and
有什么区别?
来自 https://projectreactor.io/docs/core/release/reference/index.html#which-operator:
[If you] have a sequence but [you are] not interested in values and [you] want to switch to another Mono at the end, [use] Mono#then(mono)
.
[If you] want to combine publishers by coordinating their termination from 1 Mono and any source into a Mono, [use] Mono#and
.
不幸的是,这并不能帮助我找到 #and
和 #then
行为不同的情况。
Mono#and
只是 "joins the termination signals from current mono and another source into the returned void mono"。它始终 returns Mono<Void>
并且只允许您协调两个 Mono
的终止。
Mono#then
允许您将两个 Mono
链接在一起,最终结果将由作为参数传递的 Mono
决定。从这个意义上说,Mono#then
是 Mono#flatMap
的更原始版本,唯一的区别是在 Mono#flatMap
内部你可以访问链中前一个 Mono
的结果你可以转换成另一个 Mono
实例。
除此之外,使用 Mono#then
操作将按顺序执行,而使用 Mono#and
则不能保证顺序(至少从文档中是这样)。
给定以下单声道:
Mono<Void> mono1 = Mono.fromRunnable(() -> {
System.out.println("sleep1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("mono1");
});
Mono<Void> mono2 = Mono.fromRunnable(() -> {
System.out.println("mono2");
});
Mono<Void> mono3 = Mono.fromRunnable(() -> {
System.out.println("mono3");
});
两者:
mono1
.then(mono2)
.then(mono3)
.block();
并且:
mono1
.and(mono2)
.and(mono3)
.block();
具有相同的输出:
sleep
mono1
mono2
mono3
在这种情况下 Mono#then
and Mono#and
有什么区别?
来自 https://projectreactor.io/docs/core/release/reference/index.html#which-operator:
[If you] have a sequence but [you are] not interested in values and [you] want to switch to another Mono at the end, [use]
Mono#then(mono)
.[If you] want to combine publishers by coordinating their termination from 1 Mono and any source into a Mono, [use]
Mono#and
.
不幸的是,这并不能帮助我找到 #and
和 #then
行为不同的情况。
Mono#and
只是 "joins the termination signals from current mono and another source into the returned void mono"。它始终 returns Mono<Void>
并且只允许您协调两个 Mono
的终止。
Mono#then
允许您将两个 Mono
链接在一起,最终结果将由作为参数传递的 Mono
决定。从这个意义上说,Mono#then
是 Mono#flatMap
的更原始版本,唯一的区别是在 Mono#flatMap
内部你可以访问链中前一个 Mono
的结果你可以转换成另一个 Mono
实例。
除此之外,使用 Mono#then
操作将按顺序执行,而使用 Mono#and
则不能保证顺序(至少从文档中是这样)。