【问题标题】:Reduce GroupedFlux in reactor减少反应堆中的 GroupedFlux
【发布时间】:2018-02-28 15:36:34
【问题描述】:

我有一个通量,其中包含不同的对象类型,我希望按类型对元素进行分组,然后减少每个组。

这里有一个简单的代码来做到这一点。

    Flux<Item> item=Flux.just(new Item("item1"), new Item("item2"));
    Flux<Item2> item2=Flux.just(new Item2(4.0f), new Item2(2.0f));

    Flux<Object> objects=Mono.empty().concatWith(item).concatWith(item2);       
    Flux<GroupedFlux<Object>> groups=objects.groupBy(value -> value.getClass());

如何按类型减少每个流量?enter code here

【问题讨论】:

    标签: java reactive-programming project-reactor


    【解决方案1】:

    我在 gitter 上找到了解决方案。感谢@simonbasle 和@osi 的反应。

    https://gitter.im/reactor/reactor

    关键是方法 flatMap 并使用该键来区分值。

    groups.flatMap(gf -> {
            if(gf.key()==Item.class) {
                return gf.reduce(new Item(""), (a, b) -> {
                    return new Item(a.getValue()+((Item)b).getValue());
                });
            }
            else if(gf.key()==Item2.class) {
                return gf.reduce(new Item2(0.0f), (a, b) -> {
                    return new Item2(a.getValueF()+((Item2)b).getValueF());
                });
            }
            throw new IllegalArgumentException("unknown key: "+gf.key());
        });
    

    【讨论】: