gpt4 book ai didi

kotlin - 如何使用 kotlinx-coroutines-reactive 处理空场景?

转载 作者:行者123 更新时间:2023-12-02 12:18:29 33 4
gpt4 key购买 nike

kotlinx-coroutines-reactive使 org.reactivestreams.PublisherawaitXXX方法:

val person = peopleReactiveRepository.findById(personId).awaitSingle()

如果通过人员 ID 找不到任何人员,则此调用将抛出 NoSuchElementException 和 这个异常不能直接在用户代码中处理 .和 Spring MVC ExceptionHandler无法将此异常转换为用户友好的响应。
java.util.NoSuchElementException: No value received via onNext for awaitSingle
at kotlinx.coroutines.experimental.reactive.AwaitKt$awaitOne$$inlined$suspendCancellableCoroutine$lambda$1.onComplete(Await.kt:131) ~[kotlinx-coroutines-reactive-0.22.1.jar:na]
at reactor.core.publisher.StrictSubscriber.onComplete(StrictSubscriber.java:123) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:1327) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onComplete(FluxHide.java:137) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:130) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:96) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at com.mongodb.reactivestreams.client.internal.ObservableToPublisher$1.onComplete(ObservableToPublisher.java:78) ~[mongodb-driver-reactivestreams-1.6.0.jar:na]

我能想到的方法之一如下:
val person = peopleRepository.findById(personId).awaitFirstOrDefault(null)

if (person == null) {
// do something
}

但我不认为这是一种优雅的方式。例如,可以提供一个名为 awaitSingleOptional 的方法。 .

有没有更好的 Kotlin 方法来处理这种情况?

最佳答案

没有标准Optional Kotlin 中的包装器。您可以使用 the let function对于此类情况:

val person = peopleRepository.findById(personId).awaitFirstOrDefault(null)?.let {
// do
}

如果 await 表达式的计算结果为默认值 null , let调用也将评估为 null .如果您需要处理这种情况, Elvis operator可以使用:
.let {...} ?: throw IllegalStateException()

关于kotlin - 如何使用 kotlinx-coroutines-reactive 处理空场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48617490/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com