Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Type handling in RxJava with Kotlin

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.

like image 545
Stefan Medack Avatar asked Jan 03 '23 17:01

Stefan Medack


2 Answers

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.

like image 191
nhaarman Avatar answered Jan 07 '23 17:01

nhaarman


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?")

like image 29
Kiskae Avatar answered Jan 07 '23 16:01

Kiskae