A reference to the field inside the CompletableFuture, which may again be CompletableFuture: java

I am calling a service that returns CompletableFuture.

The output structure is as follows.

Class Output {
    public String name;
    public Integer age;
}

And I want to make a call for service, and I want to continue execution until the name appears.

Sort of,

CompletableFuture<Output> futureOutput = makeServiceCall(input);
String name = futureOutput.get().name;
processName(name); // which will do some costly operations and make use of the name at the end. 

In the above approach, I need to wait until mine futureOutputis ready, although I need it only later.

I am looking for something like an approach below.

CompletableFuture<Output> futureOutput = makeServiceCall(input);
CompletableFuture<String> futureName = futureOutput.get().name; // This is wrong, but can we create a reference in a similar way?
processName(futureName); // which will do some costly operations and make use of the name at the end. 

It’s good for me to change the signature processNamefrom Stringto CompletableFuture<String>, but not to CompletableFuture<Output>, because Outputit makes no sense for this method.

What are the suggested ways to have a future link that is a field of the future.

+4
2

CompletableFuture.thenApplyAsync

JavaDoc:

CompletionStage, , , , .

( T - processName):

CompletableFuture<Output> future = makeServiceCall(input);
CompletableFuture<T> result = future.thenApplyAsync(o -> processName(o.name));

, makeServiceCall CompletableFuture, CompletableFuture processName - .

, , CompletableFuture.thenAcceptAsync, , processName :

CompletableFuture<Output> future = makeServiceCall(input);
CompletableFuture<Void> result = future.thenAcceptAsync(o -> processName(o.name));

, , , CompletableFuture.exceptionally. , , Exception.

:

makeServiceCall(input)
    .thenApplyAsync(Output::getName)
    .thenAcceptAsync(this::processName)
    .exceptionally(e -> {
        //log the error
        System.out.printf("Oops - %s%n", e);
        //return some useful default value
        return ProcessingResult.SUCCESSFUL;
    });

( - async) . Thread, ; , .

+6

, :

CompletableFuture<Output> futureOutput = makeServiceCall(input);
futureOutput.thenAcceptAsync(output -> processName(output.name));

( thenAccept, ).

0

All Articles