4

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.

1

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why would you prefer introducing a new custom Optional type if you already have nullable types in the type system that perfectly cover this case?
Because the reactive streams don't allow null values.
Ah, wasn't aware of that. Sorry!
1

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

1 Comment

Thanks for the reply. So what I am doing right now is the desired behaviour: if the list of Conferences is null, I do not consider this being an error but as the absence of conferences. So what I am doing right now is actually working, but I felt like there is a better way of handling this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.