Sequential composition for arbitrary number of calls in Vertx with Futures

前端 未结 3 1537
余生分开走
余生分开走 2020-12-18 07:48

We use Futures in vertx in examples like:

Future fetchVehicle = getUserBookedVehicle(routingContext, client);

        fetchVehicle.compose         


        
3条回答
  •  时光取名叫无心
    2020-12-18 08:30

    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.

提交回复
热议问题