When using RxJava2 in Java I have the advantage of map()
filtering emitted null values automatically. However with nullable types in Kotlin I end up doing something like this:
val loadConferencesSingle = service.getConferences()
.map { it.conferences ?: listOf<Conference>() }
The call service.getConferences()
in this case is a Single emitting a ConferecesResponse
which looks like
data class ConferencesResponse(val conferences: List<Conference?>? = null)
So in case the complete emitted list of conferences is null, I ended up using the Elvis operator to emit an empty list instead. Emitting a null in map
is not possible.
Has anybody a clue, how to handle nullable types better in RxJava with Kotlin? I already like this solution and its terseness, but I've got the feeling that there are even better ways to handle this.
Optional
is a completely valid type for this in Kotlin. The absence of a value is also a result. You could create a simple data class and function like so:
data class Optional<T>(val value: T?)
fun <T> T?.carry() = Optional(this)
Optionally, you could create some simple extension functions to make subsequent operators easier:
fun <T, R> Observable<Optional<T>>.mapNullable(mapper: (T?) -> R?) : Observable<Optional<R>>
= map { mapper(it.value).carry() }
fun <T, R> Observable<Optional<T>>.mapFromNullable(mapper: (T?) -> R) : Observable<R>
= map { mapper(it.value).carry() }
..and so on.
It entirely depends on what is considered a valid result. Does a lack of conferences
mean there are none? Then the empty list is an appropriate substitute. If it is not meant to happen then throwing an exception might be the appropriate response.
In addition throwing an exception also works with the elvis operator: it.conferences ?: throw IllegalStateException("Why is it null?")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With