Java 降低反应器中的总通量
我有一个通量,其中包含不同的对象类型,我希望按类型对元素进行分组,然后减少每个组 下面是一个简单的代码来实现这一点Java 降低反应器中的总通量,java,reactive-programming,project-reactor,Java,Reactive Programming,Project Reactor,我有一个通量,其中包含不同的对象类型,我希望按类型对元素进行分组,然后减少每个组 下面是一个简单的代码来实现这一点 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()
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());
如何按类型减少每个流量?在此处输入代码我在gitter上找到了解决方案。感谢@simonbasle和@osi的反应能力 关键是方法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());
});
我在gitter上找到了解决方案。感谢@simonbasle和@osi的反应能力 关键是方法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());
});