We use Futures in vertx in examples like:
Future<JsonObject> fetchVehicle = getUserBookedVehicle(routingContext, client);
fetchVehicle.compose(vehicleJson -> vehicleDoor(routingContext, client, vehicleJson, lock)).setHandler(
asyncResult -> {
if (asyncResult.succeeded()) {
LOG.info("Door operation succeeded with result {}", asyncResult.result().encode());
handler.handle(Future.succeededFuture(new AsyncReply(200, "OK")));
}
else {
handler.handle(Future.failedFuture(asyncResult.cause()));
}
});
where we handle 2 calls for example.
OR I have another snippet where I can handle any number of methods:
List<Future> futures = new ArrayList<>();
conversation.getRequestList().forEach(req -> {
Future<Message<Object>> senderFuture = Future.future();
vertx.eventBus().send(AbstractOEMClientVerticle.ADDRESS, JsonObject.mapFrom(req), deliveryOptions, senderFuture.completer());
// sent successfully. save the replyAddress and the conversation for later/callback
log.info("Saving the conversation for the request.", conversation.getReplyAddress());
pendingCommands.put(req.getBody().getString(MSG_ID), conversation);
futures.add(senderFuture);
});
CompositeFuture.all(futures).setHandler(ar -> {
if (ar.succeeded()) {
handler.handle(Future.succeededFuture());
} else {
log.error("forwardToVWClient VW got result : {}", ar.cause());
handler.handle(Future.failedFuture(ar.cause()));
}
});
Here we are chaining all the requests in the conversation.getRequestList()
without knowing their count in advance.
But the shortcoming of .all()
method is that, we have no control on the order.
How can I chain any number of methods with Vertx Futures (without knowing the exact count of the calls) ?
EDIT:
The official guide talks about sequential composition but the example given has 3 calls. It does not explain how to do it for arbitrary number of calls.
See "Sequential composition" in http://vertx.io/docs/vertx-core/java/
I hope it is clear.
Here's something handy. Hope it helps.
If you want to feed the response from the previous request to the next request, and suppose you have different handlers for each response. You can add a helper method
And then change your code like this
But there is a limitation for this implementation which requires each chained
Future
must have the same type parameterT
.Here is a solution using
map & reduce
that executes a method in an orderly fashion and returns the accumulated result in the form of aFuture<String>
can be used as in the example below:
where
sendApiRequestViaBus
is:I hope it helps.