Home > database >  How to access value emitted by Flux in subscription
How to access value emitted by Flux in subscription

Time:12-02

The items emitted by Flux (in this case "Red", "White", "Blue") are passed to an external service call. I am getting the response value from external service in returnValue. How do I map the elements sent to the external service with the response received?

@Log4j2
@SpringBootApplication
class FluxFromIterableAccessFlatMapValue implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {

        Flux.just("Red", "White", "Blue").
                flatMap(colors -> Mono.fromCallable(() -> {
                    // > Call to external service made here.
                    return "Return value from external Service call.";
                })).subscribeOn(Schedulers.single())
                .subscribe(returnValue ->
                        log.info("Need to access which element produced this response?"  
                                "Is it response for Red, White or Blue? "   returnValue));

    }
}

CodePudding user response:

I would simply use a Tuple (or any other wrapper) to pair each response with the corresponding color like this:

Mono<Tuple2<String, String>> makeExternalCall(String color) {
     return Mono.fromCallable(() -> {
            // > Call to external service made here.
            return "Return value from external Service call for color: "   color;
        })
        .map(response -> Tuples.of(color, response));
}
Flux.just("Red", "White", "Blue")
    .flatMap(this::makeExternalCall)//Flux<Tuple2<String, String>>
    .subscribeOn(Schedulers.single())
    .subscribe(returnValue -> log.info("Is it response for Red, White or Blue? "   returnValue));

Sample response:

Is it response for Red, White or Blue? [Red,Return value from external Service call for color:  Red]
Is it response for Red, White or Blue? [White,Return value from external Service call for color:  White]
Is it response for Red, White or Blue? [Blue,Return value from external Service call for color:  Blue]
  • Related