Search code examples
kotlinreactive-programmingreactor

switchIfEmpty is always called


I have a method like this:

fun getActiveVersionWithCacheMiss(type: String): Mono<ActiveVersion> {
        return activeVersionRepository.findByType(type)
                .switchIfEmpty(
                        Mono.defer(return persist(ActiveVersion(type,1)))
                )
    }

persist method is a simple method that saves active version:

fun persist(activeVersion: ActiveVersion): Mono<ActiveVersion>{...}

In my test I mocked activeVersionRepository to return a simple value for findByType. During debug activeVersionRepository.findByType(type).block() evaluates to a value and is definitely not empty. I'm wondering why despite using defer switchIfEmpty is still called?


Solution

  • The problem is return. The argument of switchIfEmpty needs to be evaluated regardless of whether findByType emits a value, which means the argument of defer needs to be evaluated, and return will return out of the entire function getActiveVersionWithCacheMiss.

    Though I don't see how this code can compile; return persist(...) doesn't have a value which Mono.defer can use. Do you actually have braces {}, not parentheses () somewhere?