Search code examples
kotlinandroid-livedata

How to Observe LiveData with custom pair class in Kotlin


I am trying to observe the LiveData for the method which returns custom pair having 2 values. I want the observable to be triggered when I change either one of the values. But it is not getting triggered. Following is the code:

CustomPair.kt

data class CustomPair<T, V>(
    var first : T,
    var second : V
)

Observable:

falconViewModel.getPlanet1Name().observe(this) {
    planet1.text = it.first
    planet1.isEnabled = it.second
}

Getter and setter methods in ViewModel falconViewModel

private val planet1EnabledAndText = MutableLiveData<CustomPair<String, Boolean>>()

fun getPlanet1Name() : LiveData<CustomPair<String, Boolean>> {
    return planet1EnabledAndText
}

fun setPlanet1Name(planetName : String, visibility : Boolean) {
    planet1EnabledAndText.value?.run {
        first = planetName
       second = visibility
    }
}

Can't we observe the value in such case? Please help what is wrong here.


Solution

  • It started working when I tried to set a new value of CustomPair instead of modifying the existing values in the object. Replaced

    planet1EnabledAndText.value = CustomPair(planetName, visibility)
    

    with

    planet1EnabledAndText.value?.run {
            first = planetName
           second = visibility
        }
    

    and it worked.