https://kotlinlang.org logo
Title
g

George

01/27/2023, 11:17 AM
Hi folks, just wondering why this code throws
NoSuchElementException
. Does not null count as a produced value?
suspend fun main(args: Array<String>) {
    val someThingNullable: Any? = null
    val result = mono { someThingNullable }.awaitSingle()
    println(result)
}
Thanks in advance for any answer !
d

Dmitry Khalanskiy [JB]

01/27/2023, 11:20 AM
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-reactor/kotlinx.coroutines.reactor/mono.html
null
does not count as a value. Also, reactive streams in general don't permit passing
null
values through them.
g

George

01/27/2023, 11:21 AM
Oh mb i missed that part in docs. Thanks for the help !!
r

Riccardo Lippolis

01/27/2023, 11:22 AM
you can use
.awaitSingleOrNull()
if you want to handle an empty mono as well. Keep in mind that there's a functional difference between a Mono that succeeds without emitting a value, and a Mono emitting a
null
value. But in this case you're using the
mono
function, which does not emit a value if the code block produces a
null
value, but succeeds directly.