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

问题描述 投票:4回答:2

假设我有一个findAll()方法的存储库,它返回IterableState,其中State是一个代表美国州的类,有两个字段(有getter / setter):namepopulation

我想在我的Flux中得到所有States的总体字段。我从Iterable创建一个Flux,如下所示:

Flux f = Flux.fromIterable(stateRepo.findAll());

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

int total = 0;
f.map(s -> s.getPopulation()).subscribe(p -> total += v);
return total;

但是,编译器说总的“应该是最终的或有效的最终”。显然添加final是行不通的,因为我正在尝试添加它。

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

java reactive-programming project-reactor
2个回答
7
投票

使用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
    }

3
投票

您可以从maven导入reactor额外包

io.projectreactor.addons:reactor-extra

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

© www.soinside.com 2019 - 2024. All rights reserved.