Home > Software design >  Return Mono.empty() from mono{} coroutine scope
Return Mono.empty() from mono{} coroutine scope

Time:01-28

mono {
  val abc: Int? = getSomeValue().awaitSingleOrNull

  abc
}

What will the above block return if abc is null and how to return Mono.empty() if abc is null ?

CodePudding user response:

If you look closely at mono function signature you see that:

  • It allows the lambda/closure to return a null value: block: suspend CoroutineScope.() -> T?
  • It returns a non-nullable Mono : Mono<T> (its expected, as Mono does not support null values)

The documentation states:

If the result of block is null, MonoSink.success is invoked without a value.

That may not be very clear as an explanation, but it means that in case of null value, a Mono which only send completion signal will be returned. This is the definition of an empty Mono.

We can test it with the simple program:

import kotlinx.coroutines.reactor.mono
import reactor.core.publisher.Mono

fun main() {

    var empty : Mono<String> = mono { null }

    empty.defaultIfEmpty("EMPTY !")
         .block()
        ?.let(::println)
}

It prints EMPTY !, which shows well that the null value has been treated as "no value", and produced an empty Mono.

CodePudding user response:

Mono.empty() equals to

mono {
    // .. codes
    
    null // return
}
  • Related