简体   繁体   English

如何在Flux中使用zipWith遍历元组?

[英]How to iterate over a Tuple using zipWith in Flux?

I want to iterate over a base list that offers referenceIds . 我想遍历提供referenceIds的基本列表。 Then in the next step, I want to make multiple service calls and aggregate the results in a tuple. 然后在下一步中,我要进行多个服务调用并将结果聚合到一个元组中。

Then as final step, I want to iterate over all my referenceIds , and return each generated JSONObject directly via the event stream. 然后,作为最后一步,我要遍历所有referenceIds ,并直接通过事件流返回每个生成的JSONObject

@GetMapping(value = "/test", produces = TEXT_EVENT_STREAM_VALUE)
public Flux<JSONObject> test(Integer pages) {
    pages = 1;
    return Flux.range(1, pages)
            .map(pageNumber -> Arrays.asList(1 * pageNumber, 2 * pageNumber, 3 * pageNumber)) //referenceIds for testing
            .flatMap(numbers -> Flux.fromIterable(numbers).zipWith(Mono.zip(a(numbers), b(numbers)))) //results based on reference ids
            .map(tuple -> {
                Integer number = tuple.getT1();
                Tuple2<List<String>, List<String>> lookup = tuple.getT2();

                JSONObject json = new JSONObject();
                json.put("number", number);
                json.put("someMore", <fromLookup>);
                return json;
            });
}

For this example, the return types of methods a() and b() do not matter. 对于此示例,方法a()b()的返回类型无关紧要。 The important part is: 重要的部分是:

If I just return Flux.fromIterable(numbers); 如果我只返回Flux.fromIterable(numbers); everything works fine. 一切正常。 BUT when aggregating using .zipWith() , I'm only receiving the 1st element of the numbers list. 但是当使用.zipWith()聚合时,我只收到数字列表的第一个元素。 All others are lost. 所有其他人都迷路了。 Why? 为什么?

Sidenote: I need to use .zipWith() to execute those method calls in parallel (some longer running transactions). 旁注:我需要使用.zipWith()来并行执行这些方法调用(一些运行时间更长的事务)。

All others are lost. 所有其他人都迷路了。 Why? 为什么?

From Flux class documentation: 从Flux类文档中:

Zip this {@link Flux} with another {@link Publisher} source, that is to say wait for both to emit one element and combine these elements once into a {@link Tuple2}. 将此{@link Flux}与另一个{@link Publisher}来源压缩在一起,也就是说,等待两者都发出一个元素并将这些元素组合成一个{@link Tuple2}。 The operator will continue doing so until any of the sources completes. 操作员将继续这样做,直到完成任何来源。

You can do you a() and b() calls, zip the results, and then unwind numbers list to flux and add the result like this: 您可以进行a()和b()调用,压缩结果,然后将numbers列表展开为助熔剂,并添加如下结果:

   .flatMap(numbers -> Mono.zip(a(numbers), b(numbers))
                .flatMapMany(tuple -> Flux.fromIterable(numbers).map(i -> Tuples.of(i,tuple))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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