首页 > 解决方案 > 如何使用每个 Flux 元素获得的 Mono 的值过滤 Flux?

问题描述

假设我有一个Flux<User>和另一个Mono<Department>Department有和 id 和部门名称。

我有一项服务可以返回用户所属的部门:

departmentService.getByUserId(userId: Int) : Mono<Department>

我想过滤不在部门中的用户(departmentService.getByUserId(userId: Int)返回一个空的 Mono)或在部门名称不是 HR 的部门中的用户。如何才能做到这一点?

users.flatMap { user ->
    departMentService.getByUserId(user.id)
    ...
}

标签: springspring-webfluxproject-reactor

解决方案


我的解决方案包括使用 Pair 来传播我在过滤器中需要的信息的聚合:

users.flatMap { user ->
    departMentService.getByUserId(user.id)
       .map { Pair(user, it) }
}.filter { it.second == null || it.second.departmentName != "HR" }

推荐阅读