We use Futures in vertx in examples like:
Future fetchVehicle = getUserBookedVehicle(routingContext, client);
fetchVehicle.compose
Here is a solution using map & reduce
that executes a method in an orderly fashion and returns the accumulated result in the form of a Future
public static Future chainCall(List list, Function> method){
return list.stream().reduce(Future.succeededFuture(),// the initial "future"
(acc, item) -> acc.compose(v -> method.apply(item)), // we return the compose of the previous "future" with "future" returned by next item processing
(a,b) -> Future.future()); // not used! only useful for parallel stream.
}
can be used as in the example below:
chainCall(conversation.getRequestList(), this::sendApiRequestViaBus);
where sendApiRequestViaBus
is:
/**
* @param request The request to process
* @return The result of the request processing.
*/
Future sendApiRequestViaBus(ApiRequest request) {
Future future = Future.future();
String address = CommandUtilsFactory.getInstance(request.getImplementation()).getApiClientAddress();
log.debug("Chain call start msgId {}", request.getId());
vertx.eventBus().send(address, JsonObject.mapFrom(request), deliveryOptions, res -> {
log.debug("Chain call returns {}", request.getId());
if (res.succeeded()) {
future.complete("OK");
} else {
future.fail("KO");
}
});
return future;
}
I hope it helps.