Search code examples
androidandroid-livedatamutablelivedata

How to use MutableLiveData and LiveData in Android?


I have used MutableLiveData and LiveData in the 3 ways below and see no difference.

    // 1
    private val _way1 = MutableLiveData<Boolean>()
    val way1 get() = _way1

    // 2
    private val _way2 = MutableLiveData<Boolean>()
    val way2: LiveData<Boolean> = _way2

    // 3
    var way3 = MutableLiveData<Boolean>()
        private set

Can you explain it to me?


Solution

  • 1/

    • _way1 is private and its value can be changed
    • way1 is just a public version of _way1, everything is the same. This class and other classes can access and change its value whatever they want.

    This usage is meaningless in practice.

    2/

    • _way2 is private and its value can be changed
    • way2 is public, and it's just a LiveData so it doesn't have setValue and postValue methods so its value cannot be changed. (LiveData is the parent class of MutableLiveData).

    This is a recommended way, it lets other classes observe this live data by accessing way2 but cannot change it, only the current class can change the value by modifying _way2, protecting it from being changed outside of your scope.

    Read more about object encapsulation in OOP

    3/

    • way3 is public and its value can be changed
    • Using var here because the developer wants to recreate it. Although you protect the variable by adding private set, other classes can still change the value by accessing the variable and calling setValue or postValue because it's still a Mutable one.

    So this usage is still dangerous and to my point, unnecessary to use var for a LiveData object.