You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

响应式编程中如何不借助列表将Uni<List<Fruit>>改写为Multi类型

MongoDB反应式查询Uni转Multi正确实现方案

错误点说明

  • 原有实现中collectItems().asList()的作用就是将查询得到的Multi<Book>流聚合成Uni<List<Book>>,要返回Multi只需要删除这层聚合逻辑即可
  • 你尝试的版本API使用不够规范,部分旧版Mutiny中transform().byFilteringItemsWith()已被标记为废弃,可能出现兼容性问题导致运行异常

正确实现代码

public Multi<Book> findAll(List<String> authors) {
    return getCollection().find(Filters.all("authors", authors))
            // 过滤空文档避免转换时报错
            .select().where(Objects::nonNull)
            // 将文档对象转换为业务实体
            .map(Book::from)
            // 无匹配数据时抛出异常
            .onCompletion().ifEmpty()
            .failWith(new NoSuchElementException("couldn't find the Authors"));
}

补充说明(基于PanacheMongo场景)

如果你项目中使用了Quarkus PanacheMongo扩展,也可以直接对原有返回Uni<List<Book>>的方法做拆分,写法更简洁:

public Multi<Book> findAll(List<String> authors) {
    // 调用原有返回Uni<List<Book>>的查询逻辑
    return getCollection().find(Filters.all("authors",authors)).map(Book::from).collectItems().asList()
            // 将List拆分为逐个发射的Multi流
            .onItem().disjoint()
            .onCompletion().ifEmpty()
            .failWith(new NoSuchElementException("couldn't find the Authors"));
}

内容的提问来源于stack exchange,提问作者user2699130

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:45:03