Sequential composition for arbitrary number of calls in Vertx with Futures

前端 未结 3 1546
余生分开走
余生分开走 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:26

    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

    private  Future chain(Future init, List>> handlers) {
        Future result = init;
        for (Function> handler : handlers) {
            result = result.compose(handler);
        }
        return result;
    }
    

    And then change your code like this

        Future fetchVehicle = getUserBookedVehicle(routingContext, client);
    
        Function> vehicleResponseHandler = vehicleJson ->
            vehicleDoor(routingContext, client, vehicleJson, lock);
    
        Function> anotherTrivialHandler = someJsonObj -> {
            // add here new request by using information from someJsonObj
            LOG.info("Hello from trivial handler {} ", someJsonObj);
            return Future.succeededFuture(someJsonObj);
        };
    
        List>> handlers = new ArrayList<>();
    
        handlers.add(vehicleResponseHandler);
        handlers.add(anotherTrivialHandler);
    
        chain(fetchVehicle, handlers).setHandler( asyncResult -> {
            if (asyncResult.succeeded()) {
                handler.handle(Future.succeededFuture(new AsyncReply(200, "OK")));
            } else {
                handler.handle(Future.failedFuture(asyncResult.cause()));
            }
        });
    

    But there is a limitation for this implementation which requires each chained Future must have the same type parameter T.

提交回复
热议问题