简体   繁体   English

如何迭代 Flux 以产生新的 Flux 并仍然以 Reactive 方式工作?

[英]How to iterate on a Flux to produce a new Flux and still work in a Reactive way?

I have 2 methods, respectively producing a Flux<String> and a Flux<Integer> .我有 2 种方法,分别生成Flux<String>Flux<Integer>

public Flux<String> buildName() {
        return Flux.just(personProcessor.buildName());
    }

public Flux<Integer> computeAge() {
        return Flux.just(personProcessor.computeAge());
    }

These methods generate randomized values to populate a Person object.这些方法生成随机值来填充一个人 object。

Now I would like to iterate and create X Person with randomized values in each of them.现在我想迭代并创建 X Person,每个人都有随机值。

I have created a new Flux ( processor is the name of the service holding the methods):我创建了一个新的 Flux( processor是持有方法的服务的名称):

Flux<Person> persons = Flux.zip(processor.buildName(), processor.computeAge(),
                (name, age) -> Person.builder().name(name).age(age).build() );

My problem is that when I iterate with a regular loop on the "persons" Flux, I always get Person objects with the same values for name and age.我的问题是,当我在“人员”Flux 上使用常规循环进行迭代时,我总是得到具有相同名称和年龄值的 Person 对象。 I think it's normal because my loop only subscribes to the Flux and then get the same "first" object of the Flux.我认为这很正常,因为我的循环只订阅了 Flux,然后得到了 Flux 的相同“第一个”object。 I just don't know how to iterate on the Flux "persons" so that I will obtain each time a Person object with its own name and age values.我只是不知道如何迭代 Flux“人”,以便每次都能获得一个具有自己的姓名和年龄值的人 object。

How can I iterate X times over this Flux in order to get X Person objects with randomized values?我如何在此 Flux 上迭代 X 次以获得具有随机值的 X Person 对象?

Of course, this iteration should also produce a Flux that will let me process the Person object.当然,这个迭代也应该产生一个 Flux 来让我处理 Person object。

You can simplify it as follows:您可以按如下方式简化它:

Flux.range(1, n)
        .map(i -> Person.builder()
                   .name(personProcessor.buildName())
                   .age(personProcessor.computeAge())
                   .build())

Besides Ikatiforis's most simple solution, you can also do the following which resembles your original solution.除了 Ikatiforis 最简单的解决方案外,您还可以执行以下类似于原始解决方案的操作。 This can be useful if the random values are provided in some asynchronous way.如果以某种异步方式提供随机值,这将很有用。

public Flux<String> buildName() {
    return Mono.fromCallable(() -> personProcessor.buildName()).repeat();
}

public Flux<Integer> computeAge() {
    return Mono.fromCallable(() -> personProcessor.computeAge()).repeat();
}

And then the zip part is pretty much the same:然后zip部分几乎相同:

Flux<Person> persons = Flux.zip(processor.buildName(), processor.computeAge(),
        (name, age) -> Person.builder().name(name).age(age).build())
    .take(X);

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

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