2

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?

Alejandro
  • 102
  • 9

1 Answers1

3

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

IR42
  • 8,587
  • 2
  • 23
  • 34
  • First of all, many thanks for the response!! I did not know about that... But I have one doubt, if I change it to ```var```, how would you declare the initialization or the setter in order to keep LiveData value? – Alejandro Nov 18 '20 at 12:44
  • @Alejandro why do you need `var` and setter if you need to keep LiveData value? – IR42 Nov 18 '20 at 14:44
  • hmm if I understood well backing fields I need to change it to `var`, otherwise it will not keep LiveData value as it happens now – Alejandro Nov 18 '20 at 16:55
  • @Alejandro use code from my answer, it will create backing field – IR42 Nov 18 '20 at 17:01
  • Many thanks for it! It worked! Sorry, I did not read properly your answer, got it. Again, thank you so much for investing the time for explaining it! – Alejandro Nov 26 '20 at 11:36