我有这样的方法:
fun getActiveVersionWithCacheMiss(type: String): Mono<ActiveVersion> {
return activeVersionRepository.findByType(type)
.switchIfEmpty(
Mono.defer(return persist(ActiveVersion(type,1)))
)
}
persist方法是保存活动版本的简单方法:
fun persist(activeVersion: ActiveVersion): Mono<ActiveVersion>{...}
在我的测试中,我模拟了activeVersionRepository以为findByType返回一个简单值。在调试过程中,activeVersionRepository.findByType(type).block()
会得出一个值,并且绝对不能为空。我想知道为什么尽管使用了延迟switchIfEmpty仍然被调用?
问题是return
。无论switchIfEmpty
是否发出值,都需要对findByType
的自变量求值,这意味着defer
的自变量需要求值,并且return
将返回整个函数getActiveVersionWithCacheMiss
。我假设您实际上有括号{}
,而不是在某处用括号()
括起来,否则完全不应该编译。