Ankur Chaudhari
Ankur Chaudhari

Reputation: 141

How to create a sequence of Mono at runtime

I am trying to create a sequence of Mono dynamically based on the user input. I am calling rest APIs and getting the ClientResponse in Mono. My use cases are to call 2 or more APIs in a sequence and input payload of next API is dependent on the output of the previous API.

My hard coded sequence operation is looking like


    public Mono<ResponseEntity> processSequentially(ServerHttpRequest request, JsonNode reqBody) {
            RequestData reqData = this.prepareReqMetadata(request, reqBody);
            return commonConnector.getApiResponse(reqData)
                    .flatMap(resp -> resp.bodyToMono(JsonNode.class))
                    .flatMap(respBody -> getApiResponse(request, metadataRequestBuilder, respBody))
                    .flatMap(resp -> resp.bodyToMono(JsonNode.class))
                    .flatMap(respBody -> getApiResponse(request, listingRequestBuilder, respBody))
        }

This is working fine but I want to make this method generic. I want to take all the required parameters from the user in a List of POJO and create the flatMap sequence based on the list input. So if the length of List is 2 there will 2 flatMap sequence and if length is 3 or more, number of flatMap will also be 3 or more.

Upvotes: 0

Views: 715

Answers (1)

arap
arap

Reputation: 509

Nothing happens until you subscribe, so you can apply transformation in a simple loop.

public Mono<ResponseEntity> processSequentially(ServerHttpRequest request, List<JsonNode> reqBody) {
    RequestData reqData = this.prepareReqMetadata(request, reqBody);

    Mono ret = commonConnector.getApiResponse(reqData);

    reqBody.forEach(jsonNode -> ret.flatMap(resp -> resp.bodyToMono(JsonNode.class))
                                .flatMap(respBody -> getApiResponse(request, metadataRequestBuilder, respBody))
    );

    return ret;
}

Upvotes: 1

Related Questions