Mono/Flux . defer 很重要,懶加載
then里面所有的代碼都是餓漢式的,所以then里要用 defer
map/flatMap/then是常用的三個方法
使用map/flatMap則不會出現代碼執(zhí)行順序問題
而使用then,則可能會出現順序問題亏掀,取決于是否封裝成方法
Mono/Flux后面跟 then()方法要注意以下點(代碼執(zhí)行順序錯亂問題):
1.如果直接在then()括號內部直接寫Mono/Flux則不會有問題
2.如果then()括號內部是方法(就是把1上面的Mono/Flux包到方法里)角塑,則順序會先走方法里的代碼,再走then前面的代碼轴咱,順序錯亂
idea斷點看下面幾個方法
正常的
@Test
public void test28(){
Mono.fromSupplier(() -> {
int a = 11;
return a;
}).then(Mono.fromSupplier(() -> {
int b = 222;
return b;
}).then())
.switchIfEmpty(Mono.fromSupplier(() -> {
int c = 333;
return c;
}).then())
.subscribe(x -> System.out.println(x));
}
有問題的(跟上面一模一樣的代碼,只不過把上面代碼封裝成方法)
@Test
public void test28(){
Mono.fromSupplier(() -> {
int a = 11;
return a;
}).then(aaa1())
.switchIfEmpty(aaa2())
.subscribe(x -> System.out.println(x));
}
public Mono<Void> aaa1(){
return Mono.fromSupplier(() -> {
int b = 222;
return b;
}).then();
}
public Mono<Void> aaa2(){
return Mono.fromSupplier(() -> {
int c = 333;
return c;
}).then();
}