[可能重复,但到目前为止我还没有找到]
考虑以下代码:
Mono.just(myVar)
.flatMap(MyClass::heavyOperation)
.flatMap(MyClass::anotherHeavyOperation)
.flatMap(res -> doSomething(res, MyClass.heavyOperation(myVar)));
为了提高性能,我不想用相同的输入调用两次MyClass.heavyOperation(myVar)
。
如何在第四个操作中重用第二个操作的结果?我想这样做,这是禁止的:
Object myObj;
Mono.just(myVar)
.flatMap(var -> {
myObj = MyClass.heavyOperation(var);
return myObj;
})
.flatMap(MyClass::anotherHeavyOperation)
.flatMap(res -> doSomething(res, myObj));
可能最好的解决方案是将使用myObj
的所有内容放在同一个管道步骤中。
像这样:
Mono.just(myVar)
.flatMap(MyClass::heavyOperation)
.flatMap(myObj -> MyClass.anotherHeavyOperation(myObj)
.flatMap(res -> doSomething(res, myObj)));
使用myObj
的步骤又可以被分解为许多较小的子管道。
您可以在第二个平面地图中创建一个元组:
Mono.just(myVar)
.flatMap(MyClass::heavyOperation)
.flatMap(x -> Tuples.of(x, MyClass.anotherHeavyOperation(myVar))
.flatMap(res -> doSomething(res.getT2(), res.getT1()));
考虑保持范围:
Mono.just(myVar)
.flatMap(var -> {
Object myObj = MyClass.heavyOperation(var);
return MyClass.anotherHeavyOperation(myObj)
.flatMap(res -> doSomething(res, myObj));
});
您可以将Mono
保存为变量,然后在Mono
之后再次使用anotherHeavyOperation
将其压缩。
var heavyOperation = Mono.just(myVar)
.flatMap(MyClass::heavyOperation)
.cache();
heavyOperation
.flatMap(MyClass::anotherHeavyOperation)
.zipWith(heavyOperation, (res, ho) -> doSomething(res, ho));