简体   繁体   中英

How to access value emitted by Flux in subscription

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));

    }
}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM