有没有办法"branch"和组合两个期货,同时保持单级看涨期权链?



我有一连串这样的调用:

return doFirst.thenCompose(a -> {
return doSecond(a);
}).thenCompose(b -> {
return doThird(b);
}).thenCompose(c -> {
return doFourth(c);
});

当然是简化的。现在,我需要添加另一个呼叫。

return doWithThird(b);

这可以与doThird同时发生,所以我看到的一种方法是嵌套一个thenCombine

return doFirst.thenCompose(a -> {
return doSecond(a);
}).thenCompose(b -> {
return doThird(b).thenCombine(doWithThird(b), (b1, b2) -> {
return doSomethingWithTheThirds(b1, b2);
});
}).thenCompose(c -> {
return doFourth(c);
});

不过我只是好奇,有没有办法在不嵌套的情况下做到这一点?继续单级调用链?

如果您接受使用局部变量,则可以避免 lambda 表达式/">调用链"的嵌套:

second = doFirst.thenCompose(a -> {
return doSecond(a);
});
third = second.thenCompose(b -> doThird(b));
otherThird = second.thenCompose(b -> doWithThird(b));
return third.thenCombine(otherThird, (b1, b2) -> {
return doSomethingWithTheThirds(b1, b2);
});
}).thenCompose(c -> {
return doFourth(c);
});

这也应该有助于使您的代码更具可读性,因为具有长 lambda 的长调用链往往会失去可读性。

当然,如果您想减少的数量,您仍然可以内联thirdotherThird

最新更新