Search code examples
javacompletable-futureconsumer

Transpose from Consumer to CompletableFuture


I'm currently using an API which I unfortunately cannot change easily. This API has some methods in the style of this:

public void getOffers(Consumer<List<Offer>> offersConsumer) {
        final Call<List<Offer>> offers = auctionService.getOffers();
        handleGetOffers(offersConsumer, offers);
    }

It's a web api using retrofit, and it enables me to process the response in a consumer, but I much rather want to work with CompletableFutures.

I'm using the data I receive from this endpoint to compose an interface in a game, and therefore compose an inventory, that basically acts as a frontend to the api. What I want to do, is to have my composing method to wait for the consumer to finish, and then provide the processed results. This is what I have so far, but I don't know how to do the step from the consumer to the CompletableFuture:

    @Override
    public CompletableFuture<Inventory> get(Player player) {
        return CompletableFuture.supplyAsync(() -> {
            auctionAPI.getOffers(offers -> {
                //process the offers, then return the result of the processing, in form of an "Inventory"-Object.
                }

            });


        });
    }

I now need to return the result of the processing after all the Items have been received and then processed. How can I achieve this?


Solution

  • Something along the lines should work:

    @Override
    public CompletableFuture<Inventory> get(Player player) {
        CompletableFuture<Inventory> result = new CompletableFuture<>();
        CompletableFuture.supplyAsync(() -> {
            auctionAPI.getOffers(offers -> {
                //process the offers, then return the result of the processing, in form of an "Inventory"-Object.
                result.complete(inventory);
                }
    
            });
            return null;
        });
    
        return result;
    }