androidkotlinandroid-livedataandroid-livedata-transformations

Android LiveData in Transformation map is null


I am facing and issue with Android LiveData and Transformation map. I am gonna explain the case:

I have a SingleLiveEvent and LiveData as follows (one for all items and another one for items to display in screen):

val documents: SingleLiveEvent<List<DocumentData>> = SingleLiveEvent()

val itemsToDisplay: LiveData<List<DocumentData>>
        get() {
            return Transformations.map(documents) { documents ->
                return@map documents.filter { showOptionals || it.isMandatory }
            }
        }

In Fragment, after observing itemsToDisplay, if I am trying to get the value of itemsToDisplay LiveData (itemsToDisplay.value) is always null

itemsToDisplay.observe(this, Observer {
    // Inside this method I need to get a calculated property from VM which uses 
    ```itemsToDisplay.value``` and I would like to reuse across the app
    loadData(it)
})

// View Model
val hasDocWithSign: Boolean
        get() {
            return **itemsToDisplay.value**?.any { it.isSignable } ?: false
        }

Does anyone know if a LiveData does not hold the value if it is calculated using Transformation.map or it could be a potential bug?


Solution

  • When you call itemsToDisplay you get a new empty LiveData instance, because you declared it as a getter without a backing field.

    val itemsToDisplay: LiveData<List<DocumentData>>
            = Transformations.map(documents) { documents ->
                    documents.filter { showOptionals || it.isMandatory }
            }
    

    https://kotlinlang.org/docs/reference/properties.html#backing-fields