Search code examples
androidkotlinandroid-livedata

How to use LiveData into ViewModel in Android


In my application I want to use Viewmodel with LiveData and for this I used this tutorial : ViewModel with LiveData

But I have one question, why used LiveData such as below :

private val _flavor = MutableLiveData<String>("")
val flavor: LiveData<String> = _flavor

fun setFlavor(desiredFlavor: String) {
    _flavor.value = desiredFlavor
}

Why not used with below formed?

val flavor = MutableLiveData<String>()

fun setFlavor(desiredFlavor: String) {
    flavor.value = desiredFlavor
}

Please say me more information about this.


Solution

  • Why not used with below formed ?

    val flavor = MutableLiveData<String>()
    
    fun setFlavor(desiredFlavor: String) {
        flavor.value = desiredFlavor
    }
    

    In short, it violates encapsulation.

    Suppose setFlavor was more complicated:

    fun setFlavor(desiredFlavor: String) {
        flavor.value = complextLogicToValidateAndTransform(desiredFlavor)
    }
    

    You would always want anything trying to update the flavor to go through setFlavor. But with an exposed MutableLiveData object, anyone can change the flavor and bypass your checks.

    viewModel.flavor.setValue(unvalidatedAndUntransformedFlavorThatWillCauseHavok)
    

    By keeping that private and an only exposing a read-only variable, you control how the value can be updated.