【问题标题】:How to access value emitted by Flux in subscription如何在订阅中访问 Flux 发出的值
【发布时间】:2022-01-08 06:02:50
【问题描述】:

Flux 发出的项目(在本例中为“Red”、“White”、“Blue”)被传递给外部服务调用。我从returnValue 中的外部服务获取响应值。如何将发送到外部服务的元素与收到的响应进行映射?

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

    }
}

【问题讨论】:

    标签: java spring spring-boot spring-webflux project-reactor


    【解决方案1】:

    我会简单地使用元组(或任何其他包装器)将每个响应与相应的颜色配对,如下所示:

    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]
    

    【讨论】:

    • 它在地图中显示错误(响应 -> Tuples.of(颜色,响应))。错误是必需类型:Mono > 提供:Mono 不存在类型变量 T1、T2 的实例,因此 Tuple2 符合 Tuple2 推理变量 R 的边界不兼容: 等式约束: Tuple2 下界: Tuple2
    • 现在对我很好。我的问题是 Tuple2 来自 io.vavr.Tuple2 而不是 reactor.util.function.Tuple2
    猜你喜欢
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2018-07-24
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多