Mono.zip 为空

Mono.zip with null

我的代码:

Mono.zip(
            credentialService.getCredentials(connect.getACredentialsId()),
            credentialService.getCredentials(connect.getBCredentialsId())
)
.flatMap(...

从前端我们得到 connect 具有 2 个字段的对象:

connect{
aCredentialsId : UUID //required
bCredentialsId : UUID //optional
}

所以有时候第二行credentialService.getCredentials(connect.getBCredentialsId()))可以returnMono.empty

当我的第二个字段 bCredentialsId 为空时,如何编写代码为这个空的 Mono 准备?

我该怎么办?在空值的情况下 return Mono.just(new Object) 然后检查 obj.getValue != null???我需要从数据库中获取 2 个不同值的数据

我在这里更喜欢的策略是声明一个 optional() 实用程序方法,如下所示:

public class Utils {

    public static <T> Mono<Optional<T>> optional(Mono<T> in) {
        return in.map(Optional::of).switchIfEmpty(Mono.just(Optional.empty()));
    }

}

...然后允许您将第二个 Mono 转换为始终 return 可选的,因此可以执行以下操作:

Mono.zip(
        credentialService.getCredentials(connect.getACredentialsId()),
        credentialService.getCredentials(connect.getBCredentialsId()).transform(Utils::optional)
).map(e -> new Connect(e.getT1(), e.getT2()))

(...假设您有一个 Connect 对象,它当然将 Optional 作为第二个参数。)

更简单的方法是使用单声道的 defaultIfEmpty 方法。

Mono<String> m1 = credentialService.getCredentials(connect.getACredentialsId());
Mono<String> m2 = credentialService.getCredentials(connect.getBCredentialsId()).defaultIfEmpty("");

Mono.zip(m1, m2).map(t -> connectService.connect(t.getT1(), t.getT2()));

解释:如果 m2 为 null,则获取空字符串作为默认值而不是 null。

我不会在此处使用 .zip,而是使用 Connect 的可为空 属性 并将 .flatMap 与 .switchIfEmpty 结合使用。

Kotlin 版本:

val aCredentials = credentialService.getCredentials(connect.getACredentialsId())

credentialService.getCredentials(connect.getBCredentialsId())
       .flatMap { bCredentials -> aCredentials
                      .map { Connect(it, bCredentials)}
                      .switchIfEmpty(Connect(null, bCredentials)) 
        }
       .switchIfEmpty { aCredentials.map { Connect(it, null) } }