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

在Flux中使用Mono结果:如何获取Mono值用于Flux操作并返回Flux

解决方案

核心使用Mono.flatMapMany操作符即可实现需求,它可以将Mono发布的单个值转换为Flux类型的下游流,同时消除嵌套的响应式类型包装,调整后的代码如下:

public Flux<My> getMy() {
  Mono<ZonedDateTime> dateTimeMono = getDateTime();

  return dateTimeMono.flatMapMany(dateTime -> 
      reactiveMongoTemplate.find(
            new Query(Criteria.where("dateTime").gt(dateTime)),
            My.class,
            collectionName
      )
  );
}

原代码问题说明

你原来的写法无法正常运行,因为Criteria的gt方法接收的是普通数值类型,不会自动订阅你传入的dateTimeMono获取实际时间值,Mongo响应式驱动也没有能力自动处理查询条件里嵌套的响应式类型。

Mono.zip嵌套问题解决

你之前使用Mono.zip得到Mono<Flux<My>>类型,是因为没有把嵌套的Flux展开,搭配flatMapMany即可得到符合要求的Flux<My>返回值,多参数场景示例如下:

public Flux<My> getMy() {
  Mono<ZonedDateTime> startTimeMono = getStartDateTime();
  Mono<ZonedDateTime> endTimeMono = getEndDateTime();

  // 先合并多个Mono的结果,再转换为Flux
  return Mono.zip(startTimeMono, endTimeMono)
      .flatMapMany(tuple -> {
          ZonedDateTime startTime = tuple.getT1();
          ZonedDateTime endTime = tuple.getT2();
          return reactiveMongoTemplate.find(
              new Query(Criteria.where("dateTime").gt(startTime).lt(endTime)),
              My.class,
              collectionName
          );
      });
}

整个流程完全符合响应式编程规范,不需要手动订阅任何流,流的订阅触发由方法的上游调用方处理。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:06:01