kotlinrx-java2rx-kotlin2

Unexpected NullPointException with RxKotlin when mapping optionals


To start I have the following Moshi json.

@JsonClass(generateAdapter = true)
data class OrderDetails(
    @Json(name = "_id") val id: Int,
    @Json(name = "status") val status: String,
    @Json(name = "tableNo") val tableNo: Int,
    @Json(name = "serverId") val serverId: Int?,
    @Json(name = "items") val orderItems: List<OrderDetailsItem>
)

All these fields are expected to have data except for serverId. This data is fetched from the server where I can allow the user to select order.

onSeletedOrder
   .map { it.orderDetails.serverId } //blows up here apparently.
   .filterNotNull() //have tried this but it doesn't matter.
   .flatMap { findServerBy(it) }
   .map { "${it.firstname} ${it.lastname}" }

When I map to the serverId above I blow up with an NPE. It's interesting that the map (even though it is optional) does an unsafe cast afterwards. I'd expect it to maintain the optional-ness after the map. I'm assuming this is because of the bridging backwards to RxJava. Curious if anyone has a further explanation on why this is.


Solution

  • RxJava does not allow nulls inside the stream. Ideally you would perform this filter before the items enter the stream, but if you can't do that one workaround you could get away with is to use an empty string in place of null.

    onSeletedOrder
       .map { it.orderDetails.serverId.orEmpty() }
       .filter { it.isNotEmpty() }
       .flatMap { findServerBy(it) }
       .map { "${it.firstname} ${it.lastname}" }