简体   繁体   中英

Setting value for CompletableFuture within a lambda

I have the following code:

public CompletableFuture<Object> send(String message) {
    CompletableFuture<Object> response =  new CompletableFuture<>();
    KafkaProducerRecord<String, String> record = ...
    KafkaProducer producer = ...
    producer.write(record, done -> {
        if(done.succeeded()) {
            Object o = ...
            response.complete(...);
        }
        else {
            Object o = ...
            response.complete(...);
        }
    });

    return response;
}

The problem is that while response.complete() is being called and passed the correct value whether done.succeeded() is true or false, response.result is always being returned as null. response.result is only set if response.complete() is called outside the lambda expression before returning.

In the calling method I have tried the following:

CompletableFuture<IResponse> resp = this.send(message);
try {
  System.out.println(resp.get());
} catch (InterruptedException | ExecutionException e) {
  e.printStackTrace();
}

But this just hangs. The same is true when wrapping the wrapping the CompletableFuture in an Observable and then doing subscribe() on the Observable, as follows:

Observable.fromFuture(this.send(message)).subscribe(i -> {});

Can anyone assist, thanks.

response.result is always being returned as null

How did you get access to that field? It is an internal field that stores the result once it has been computed.

To get the result you need to call get() which will block until the result is ready, or isDone() to check if it is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM