在 RxJava 2 和 Reactor 中有一个 switchIfEmpty
like 方法在当前流中没有元素时切换到新流。
但是当我开始使用Minuty ,当我将我的 Quarkus 示例转换为使用 Reactive 功能时,我找不到替代方案。
目前我的解决方案是:在我的 PostRepository
,我使用异常来指示没有找到帖子。
public Uni<Post> findById(UUID id) {
return this.client
.preparedQuery("SELECT * FROM posts WHERE id=$1", Tuple.of(id))
.map(RowSet::iterator)
.flatMap(it -> it.hasNext() ? Uni.createFrom().item(rowToPost(it.next())) : Uni.createFrom().failure(()-> new PostNotFoundException()));
}
并在 PostResource
中捕获它.
@Path("{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Uni<Response> getPostById(@PathParam("id") final String id) {
return this.posts.findById(UUID.fromString(id))
.map(data -> ok(data).build())
.onFailure(PostNotFoundException.class).recoverWithItem(status(Status.NOT_FOUND).build());
}
如何返回 Uni
表示 PostRepository
中的 0 或 1 个元素,并使用 switchIfEmpty
喜欢 PostResource
中的方法为流程构建替代路径?
最佳答案
Uni
不能是空,因为它总是包含一个项目(可能是 null
)。
因此,switchIfEmpty
的等效项是 uni.onItem().ifNull().switchTo(() -> ...)
关于reactive-programming - Smallrye Mutiny 中的 switchIfEmpty 替代方案是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61140873/