Can you tell me how I can wait for the CompletableFuture list in the parent CompletableFuture, collect their result and return it?
CompletableFuture<TerminateEnvironmentResponse> future = CompletableFuture.supplyAsync(() -> {
TerminateEnvironmentResponse terminateEnvironmentResponse = new TerminateEnvironmentResponse();
List<EnvironmentDto> environmentDtoList = ...
environmentDtoList.forEach(environmentDto -> {
_cloudFormationService.destroyStack(environmentDto)
.whenComplete((result, ex) -> {
if (ex != null) {
terminateEnvironmentResponse.setError(true);
} else {
int count = terminateEnvironmentResponse.getCount();
terminateEnvironmentResponse.setCount(++count);
}
});
});
return terminateEnvironmentResponse;
});
return future;
Decided so far so ...
static <V> CompletableFuture<Collection<V>> allOf(Collection<CompletableFuture<V>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream()
.map(CompletableFuture::join)
.collect(toList()));
}
private CompletableFuture<DeleteStackResult> map(CompletableFuture<DeleteStackResponse> responseCompletableFuture) {
return responseCompletableFuture.thenApply(res -> new DeleteStackResult(res, null))
.exceptionally(ex -> new DeleteStackResult(null, ex));
}
@Data
@AllArgsConstructor
static class DeleteStackResult {
private DeleteStackResponse response;
private Throwable exception;
}
@Override public CompletableFuture<TerminateEnvironmentResponse> terminateEnvironment(UserDto userDto) {
List<CompletableFuture<DeleteStackResult>> completableFutureList = new ArrayList();
List<EnvironmentDto> environmentDtoList = _environmentService.getEnvironments();
environmentDtoList.forEach(environmentDto -> completableFutureList.add(map(_cloudFormationService.destroyStack(environmentDto))));
CompletableFuture<Collection<DeleteStackResult>> collectionCompletableFuture = allOf(completableFutureList);
CompletableFuture<TerminateEnvironmentResponse> future = collectionCompletableFuture.thenApply(resultCollection -> {
TerminateEnvironmentResponse terminateEnvironmentResponse = new TerminateEnvironmentResponse();
resultCollection.forEach(deleteStackResult -> {
int count = terminateEnvironmentResponse.getCount();
terminateEnvironmentResponse.setCount(++count);
if (deleteStackResult.getException() != null) {
terminateEnvironmentResponse.setError(true);
}
});
return terminateEnvironmentResponse;
});
return future; }
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.