簡體   English   中英

如何在訂閱中訪問 Flux 發出的值

[英]How to access value emitted by Flux in subscription

Flux發出的項目(在本例中為“Red”、“White”、“Blue”)被傳遞給外部服務調用。 我在returnValue中從外部服務獲取響應值。 我如何 map 將元素發送到外部服務並收到響應?

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

    }
}

我會簡單地使用元組(或任何其他包裝器)將每個響應與相應的顏色配對,如下所示:

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

示例響應:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM