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?
1/
This usage is meaningless in practice.
2/
LiveDataso it doesn't havesetValueandpostValuemethods 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
way2but 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/
varhere because the developer wants to recreate it. Although you protect the variable by addingprivate set, other classes can still change the value by accessing the variable and callingsetValueorpostValuebecause it's still a Mutable one.So this usage is still dangerous and to my point, unnecessary to use
varfor a LiveData object.