如果多个Mono <Object>之一为空,则取消执行

问题描述

我是反应式编程的新手。 我的代码如下,并且我无法弄清楚如何返回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);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...