打破 Completable Future 的 then apply 链

min*_*ibi 3 java completable-future

我有很多类似这样的电话。问题是下一个调用完全取决于前一个调用。如果没有任何对话,从他们那里获取消息是没有意义的,所以我只想打破这个链条。我读了一些霍尔格答案的主题,但我觉得我仍然没有完全理解这一点。有人可以给我一些基于这段代码的例子吗?

public CompletableFuture<Set<Conversation>> fetchConversations(List<Information> data, String sessionId)
{
    return myservice
        .get(prepareRequest(data, sessionId))
        .thenApply(HtmlResponse::getDocument)
        .thenApply(this::extractConversationsFromDocument);
}
public CompletableFuture<Elements> fetchMessagesFromConversation(String Url, String sessionId)
{
    return mySerice
        .get(prepareRequest(url, sessionId))
        .thenApply(HtmlResponse::getDocument)
        .thenApply(this::extractMessageFromConversation);
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*nov 5

从任何链步骤中抛出异常将跳过所有后续步骤:不会thenApply()调用任何回调,并且未来将在发生异常时得到解决。你可以用它来打破你的链条。例如,考虑以下代码:

public CompletableFuture<Set<Conversation>> fetchConversations(List<Information> data, String sessionId) {
    return myservice
            .get(prepareRequest(data, sessionId))
            .thenApply(HtmlResponse::getDocument)
            .thenApply(value -> {
                if (checkSomeCondition(value)) 
                    throw new CompletionException(new CustomException("Reason"));
                return value;
            })
            .thenApply(this::extractConversationsFromDocument)
            .exceptionally(e -> {
                // the .thenApply(this::extractConversationsFromDocument) step 
                // was not executed
                return Collections.emptySet(); //or null
            });
}
Run Code Online (Sandbox Code Playgroud)

您可以添加一个步骤,在其中检查上一步返回的值,并根据某些条件引发异常。

然后,在最后一个之后,.thenApply您可以添加一个exceptionally处理程序并返回一个空的Setnull其他内容作为不成功的结果。

您也可以省略处理exceptionally程序。在这种情况下,您必须在链的末尾捕获异常,最后调用.get()

try {
    Set<Conversation> conversations = fetchConversations(data, id).get();
} catch (InterruptedException e) {
    // handle the InterruptedException
    e.printStackTrace();
} catch (ExecutionException e) {
    // handle the ExecutionException
    // e.getCause() is your CustomException or any other exception thrown from the chain
}
Run Code Online (Sandbox Code Playgroud)