java - 仅当第一个发出的事件不符合条件时才从通量中发布下一个元素
问题描述
UserPreferenceFlux 按优先级顺序保存用户偏好信息,我们必须考虑第二偏好,只有与第一偏好不匹配。首选项匹配需要阻塞 I/O 调用。我尝试使用下面的代码,即使与用户第一偏好匹配,我也可以看到为第二偏好进行了 WebClient 调用,这是不必要的(因为第一匹配偏好已经在进行中)。
Flux<UserPreference> userPreferenceFlux = getUserPreferences();
UserPreferenceFlux
.flatMap(preference -> checkForMatch()) // Blocking IO call for match check
.filter(preference -> preference.isMatchFound())
.next(); // The Idea is to consider next preference if current preference is
// not found
解决方案
使用concatMap
而不是flatMap
.
默认情况下,flatMap 将从源请求 256 个首选项并一次处理它们。这种“一次性”行为因您checkForMatch()
似乎正在阻塞而减少,但仍然:源本身的请求比您想要的要多。
concatMap
另一方面,将一个一个地从源请求首选项,等到当前UserPreference
处理完毕后再请求下一个。
推荐阅读
- apache-camel - 如何关联 Camel ExchangeCompletedEvent 和多播/拆分?
- php - 如何将翻译放入 Laravel 表单中的数组中?
- swift - Swift:动画 uilayoutconstraints 和更改 alpha 会导致崩溃
- timezone - ISO8601 与时区和时间跨度
- export-to-csv - 从 Grafana 图表导出 CSV 中的数字格式错误
- python - 获取 KeyError:Adj。在 python 中关闭
- javascript - React - 在组件之间传递方法引用
- java - CXF 总线 - 添加具有自定义超时的 HttpConduitFeature
- node.js - 如何在 Windows 中将 npm start 添加为服务
- json - 打字稿中的 JSON 转换