问题
I am new in reactive programming. I saw that two monos could be zipped to generate a result:
Mono<Info> info = Mono.just(id).map(this::getInfo).subscribeOn(Schedulers.parallel());
Mono<List<Detail>> detail= Mono.just(petitionRequest).map(this.service::getDetails)
.subscribeOn(Schedulers.parallel());
Flux<Generated> flux = Flux.zip(detail, info, (p, c) -> {
Generated o = Generated.builder().info(c).detail(p).build();
return o;
});
As I have understood this paralelizes the two call and generate the object Generated when I call to flux.blockFirst()
How can I merge another mono to the existing two ones to generate a result? Flux.zip only accepts two monos.
Thanks in advance.
回答1:
First of all, since you are zipping Monos, it would make sense to use zip operator from Mono instead of Flux.
It has multiple overloaded versions which can accept any number of Monos.
Also, if this.service::getDetails
and this::getInfo
are blocking IO operations (HTTP request, database call, etc.) then you should use elastic Scheduler instead of the parallel one, the latter is intended for CPU intensive operations.
Sample code:
Mono<Info> info = Mono.just(id)
.map(this::getInfo)
.subscribeOn(Schedulers.elastic());
Mono<List<Detail>> detail= Mono.just(petitionRequest)
.map(this.service::getDetails)
.subscribeOn(Schedulers.elastic());
Mono<Description> description = Mono.just(id)
.map(this::callService)
.subscribe(Schedulers.elastic());
Mono.zip(info, detail, description)
.map(this::map);
private Generated map(Tuple3<Info, List<Detail>, Description> tuple3)
{
Info info = tuple3.getT1();
List<Detail> details = tuple3.getT2();
Description description = tuple3.getT3();
// build output here
}
来源:https://stackoverflow.com/questions/57141596/create-entity-from-3-different-mono