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/

    This usage is meaningless in practice.

    2/

    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/

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