问题描述
我是反应式编程的新手。
我的代码如下,并且我无法弄清楚如何返回Flux.empty()
,以防firstService.getEntity(id1)
和secondService.getEntity(id2)
返回Mono.empty()
public Flux<Entity3> method(UUID id1,UUID id2,SomeEnum value) {
var entity1Mono = firstService.getEntity(id1).log(); // <-- Mono<Entity1>
var entity2Mono = secondService.getEntity(id2).log(); // <-- Mono<Entity2>
// following code should be executed in case entity1Mono AND entity2Mono are not empty
var parrent = Flux.combineLatest(entity1Mono,entity2Mono,(entity1,entity2) -> /* build a new entity */); // <-- Flux<Entity3>
var child = Flux.from(entity2Mono)
.flatMapIterable(Entity2::getChildren)
.map(child -> /* build a new entities */); // <-- Flux<Entity3>
var entity3 = Flux.merge(parrent,child).log();
return thrirdService.insert(entity3);
}
也许上面的代码可以更优化?
解决方法
我的解决方法是:
public Flux<Entity3> method(UUID id1,UUID id2,SomeEnum value) {
var entity1Mono = firstService.getEntity(id1).log(); // <-- Mono<Entity1>
var entity2Mono = secondService.getEntity(id2).log(); // <-- Mono<Entity2>
// following code should be executed in case entity1Mono AND entity2Mono are not empty
var parrent = Flux.combineLatest(entity1Mono,entity2Mono,(entity1,entity2) -> /* build a new entity */); // <-- Flux<Entity3>
var child = entity1Mono.hasElement()
.filter(isExist -> isExist)
.flatMapMany(aBoolean -> Flux.from(entity2Mono)
.filter(entity -> CollectionUtils.isNotEmpty(entity.getChildren()))
.flatMapIterable(Entity2::getChildren)
.map(child -> /* build a new entities */)
); // <-- Flux<Entity3>
var entity3 = Flux.merge(parrent,child).log();
return thrirdService.insert(entity3);
}