如何对Reactor Flux流中的值求和?

Mar*_*ark 5 java reactive-programming project-reactor

假设我有一个存储库,其中包含一个findAll()返回Iterableof 的方法State,其中State一个类表示一个具有两个字段(带有getter/setter)的US状态:namepopulation.

我想得到State我的Flux中所有s 的总体字段的总和.我从Iterable创建一个Flux,如下所示:

Flux f = Flux.fromIterable(stateRepo.findAll());
Run Code Online (Sandbox Code Playgroud)

我有我的Flux,但我不知道总结其价值的好方法.我尝试过类似的东西

int total = 0;
f.map(s -> s.getPopulation()).subscribe(p -> total += v);
return total;
Run Code Online (Sandbox Code Playgroud)

但是,编译器说总的"应该是最终的或有效的最终".添加final显然不起作用,因为我正在尝试添加它.

如何在Flux上进行求和(或任何其他聚合函数)?

mro*_*man 8

使用reduce方法:

@GetMapping("/populations")
    public Mono<Integer> getPopulation() {
        return Flux.fromIterable(stateRepo.findAll())
                .map(s -> s.getPopulation())
                .reduce(0, (x1, x2) -> x1 + x2)
                .map(this::someFunction); // here you can handle the sum
    }
Run Code Online (Sandbox Code Playgroud)

  • `.reduce(0, (x1, x2) -&gt; x1 + x2)` 可以替换为 `.reduce(0, Integer:sum)` (3认同)

Sla*_*ava 5

您可以从maven导入reactor额外包

io.projectreactor.addons:reactor-extra

然后使用MathFlux.sumInt(integresFlux)
文档:https ://projectreactor.io/docs/core/release/reference/#extra-math