Kotlin Reactor-如何使用过滤器,如果没有';你不能通过过滤器吗?
我正试图找出正确的方法来做下面的事情Kotlin Reactor-如何使用过滤器,如果没有';你不能通过过滤器吗?,kotlin,project-reactor,reactor,Kotlin,Project Reactor,Reactor,我正试图找出正确的方法来做下面的事情 我想通过name检查数据库中是否存在记录,这是一个全局二级索引。(假设主键是id) 如果已经有一个项目具有名称,则记录id和名称,并返回一个错误 如果没有具有给定名称的项目,则继续 现在,代码结构如下所示 private fun checkExistingData(name: String): Mono<QueryResponse> { return repo.getDataByName(name) .filterWhen { M
- 我想通过
检查数据库中是否存在记录,这是一个全局二级索引。(假设主键是name
)id
- 如果已经有一个项目具有
,则记录名称
和id
,并返回一个错误名称
- 如果没有具有给定
,则继续名称的项目
private fun checkExistingData(name: String): Mono<QueryResponse> {
return repo.getDataByName(name)
.filterWhen { Mono.just(!it.hasItems()) }
.switchIfEmpty {
// log the existing id and name from QueryResponse
Mono.error(SomeCustomException))
}
.flatMap {
// proceed
}
}
private fun checkExistingData(名称:String):Mono{
return repo.getDataByName(名称)
.filterWhen{Mono.just(!it.hasItems())}
.switchIfEmpty{
//记录QueryResponse中的现有id和名称
Mono.error(SomeCustomException))
}
.平面图{
//进行
}
}
如您所见,如果我想在switchIfEmpty
子句中记录id
,我需要在其中执行repo.getDataByName(name)
,以便能够检索项目并获取项目的id
。显然,这是低效的,因为我在切换ifempty
之前已经这样做了
正确的方法是什么?在等待有关
QueryResponse
API的更多信息之前,我将假设以下几点:
-getDataByName
返回一个Mono
。此Mono
始终是有价值的,即它始终只发出一个QueryResponse
是否可以找到数据
-QueryResponse#items
是我在示例中用来访问正确行的内容。我还要假设它返回一个Flux
首先,filterWhen
在这里不有用,因为我们还有一个filter(boolean)
方法。我认为反向过滤逻辑可能更难理解
为什么不改为在flatMap
中执行所有操作
private fun checkExistingData(name: String): Mono<QueryResponse> {
return repo.getDataByName(name)
.flatMap {
if (it.hasItems())
it.items()
.single()
.doOnNext(existing -> logExisting(existing.id(), existing.name())
.then(Mono.error(SomeCustomException)
else
proceed()
}
}
private fun checkExistingData(名称:String):Mono{
return repo.getDataByName(名称)
.平面图{
if(it.hasItems())
it.items()
.single()
.doOnNext(现有->日志现有(现有.id(),现有.name())
.then(Mono.error(SomeCustomException)
其他的
继续
}
}
如果第一次调用repo.getDataByName
返回一个Mono
,并且这个Mono
是空的,那么您不需要过滤这种情况,因为管道的其余部分将不会被调用。因此我认为您可以保留开关ifempty()
要记录此特定案例,然后继续使用flatMap()
:
private fun checkExistingData(名称:String):Mono{
return repo.getDataByName(名称)
.switchIfEmpty{
//记录QueryResponse中的现有id和名称
Mono.error(SomeCustomException))
}
.平面图{
//进行
}
}
为什么不存储repo.getDataByName()的结果在变量中,然后在switchIfEmpty
中访问它?你能显示代码吗?我对reactor了解不多,所以不能正确回答,我只是建议你不要从第一行返回,而是将代码的第一行存储为变量,然后返回变量。switchIfEmpty….
其余的代码和在switchIfEmpty中,您可以访问特定的变量
,不是吗?因此,如果我理解正确,总是会发出QueryResponse
对象,但您可以通过执行hasItems()
?和hasItems()来确定是否存在条目
返回一个Mono
?如何准确访问项目?
private fun checkExistingData(name: String): Mono<QueryResponse> {
return repo.getDataByName(name)
.switchIfEmpty {
// log the existing id and name from QueryResponse
Mono.error(SomeCustomException))
}
.flatMap {
// proceed
}
}