Java CompleteableFuture .handle() 从上一个链式方法访问输入参数

Java CompleteableFuture .handle() access input parameter from previous chained method

是否可以从 .handle() 中访问先前链接的 .thenCompose() 的输入?

在接下来的block中,如果出现异常,我想减少累加的x。

@Test
public void Test() {
    Integer result = testCompletable().join();
    assertThat(result.equals(1));
}
public CompletableFuture<Integer> testCompletable() {
    CompletableFuture<Integer> result = CompletableFuture.completedFuture(0);
    for (int i = 0; i < 2; i++) {
        final int j = i;
        result = result.thenCompose(x -> {
            if (j == 1) {
              throw new RuntimeException("Manually planted ex");
            }
            x = x + 1;
            return CompletableFuture.completedFuture(x);
        }).handle((r, e) -> {
            if (e != null) {
                x = x -1;   // <-- this line doesn't compile, how to access x here?
            }
            return x;
        });
    }
    return result;
}

我原来有

.handle((r, e) -> {
                if (e != null) {
                    r = r -1;   // r is NULL here.
                }
                return r;
            })

是的,只需将未来存储在一个临时 (final) 变量中并对其调用 join() 以检索其值:

public CompletableFuture<Integer> testCompletable() {
    CompletableFuture<Integer> result = CompletableFuture.completedFuture(0);
    for (int i = 0; i < 2; i++) {
        final int j = i;
        final var oldResult = result;
        result = result.thenCompose(x -> {
            if (j == 1) {
                throw new RuntimeException("Manually planted ex");
            }
            x = x + 1;
            return CompletableFuture.completedFuture(x);
        }).handle((r, e) -> {
            var x = r;
            if (e != null) {
                // will not block since it’s guaranteed to be resolved – may throw though
                x = oldResult.join() - 1;
            }
            return x;
        });
    }
    return result;
}