【发布时间】:2019-12-21 04:55:11
【问题描述】:
这个问题很难用文字来描述,所以如果标题不符合要求,很抱歉。
我想通过 Project Reactor Flux 和 Mono 来实现一个特定的目标,乍一看这似乎很简单。
一个代码示例,在“阻塞方式”中会比长描述更好:
fun findGroupToCreateBlocking(userId: UUID, groupLabel: String): Optional<LinkUserToGroup> {
val group = lib.findGroupsOfUser(userId)
.flatMapIterable { it.items }
.filter { it.label == groupLabel }
.toMono()
.blockOptional()
if(group.isPresent) {
return Optional.empty()
}
return lib.searchGroups(groupLabel)
.flatMapIterable { it.items }
.filter { it.label == groupLabel }
.toMono()
.map { LinkUserToGroup(userId, it.id) }
.switchIfEmpty { IllegalStateException("Group $groupLabel not found").toMono() }
.blockOptional()
}
当然,我尝试在没有block 部分的情况下实现相同的目标。我最终得到了以下代码:
fun findGroupToCreateReactive(userId: UUID, groupLabel: String): Mono<LinkUserToGroup> =
lib.findGroupsOfUser(userId)
.flatMapIterable { it.items }
.filter { it.label == groupLabel }
.toMono()
.map { Optional.of(it) }
.defaultIfEmpty(Optional.empty())
.filter { g -> g.isEmpty }
.flatMap { lib.searchGroups(groupLabel)
.flatMapIterable { it.items }
.toMono()
.map { LinkUserToGroup(userId, it.id) }
.switchIfEmpty { IllegalStateException("Group $groupLabel not found").toMono() }
}
我认为(而且我不是唯一一个 ????)我们可以做得更好,而不是依赖流中间的 Optional 用法......但我没有找到任何其他解决方案.
这是我第四次与这种“模式”作斗争,所以欢迎一些帮助!
我在 Gitlab (here) 上生成了一个演示项目,其中包含机器人响应式和阻塞式实现的单元测试,以查看命题是否符合要求。如果需要,您可以分叉并使用该项目。
【问题讨论】:
标签: reactive-programming project-reactor reactive