Following is my use case that I am trying to implement using CompletableFuture class
- I have a list of ids for which I want to do an api call for each of the ids
- I want to get the response back from the api calls and save it in a list or map for further processing
- I also do not want to wait till I get the responses of all api calls. I want to set a time limit and get whatever data is available till that time.
I tried the following code but it is not working correctly
// list content
List<Integer> ids = Arrays.asList(1,2,3,4,5);
// Api call using parallel stream - not sure how I can include a time limit here so that
// I can get partial list of updatedIds based on delay settings
List<Integer> updatedIds = ids.parallelStream().map(item -> {
// api call equivalent of increment 1
return item+1;
}).collect(Collectors.toList());
// Asynchronous api call using CompletableFuture class - not sure how I can
// dynamically call the function for all items in the ids list.
// Following is what I tried to do by reading
// https://www.baeldung.com/java-completablefuture
encounterIdSet.parallelStream().forEach(id -> {
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> serviceCall(id));
});
List<Integer> = completableFuture.get(60, TimeUnit.SECONDS); // may be in incorrect location
// I want to process the list of returned integers here - whatever I am getting in 60 seconds timeout mentioned in timeout settings
// service call definition
Integer serviceCall(id){
return id +1;
}
Can you please guide me on this use case? I need 1. timeout settings with 2. asynchronous data processing of 3. unknown number of items.
I am using Java 8.
Thanks.