In many samples i see that:
class DataViewModel{
val data:LivaData<Int>
get() = _data
private val _data = MutableLiveData<Int>()
}
But more simply looks like this:
class DataViewModel{
val data = MutableLiveData<Int>()
}
so, why need this more complicated code construction with 2 fields?
It's a practice designed to restrict modification of the value from outside the class.
LiveData
is read-only.
MutableLiveData
, as the name implies, allows one to change the value it holds.
If you expose a MutableLiveData
directly, like in your second example, any code which can access that data
field could also modify the value it holds.
Exposing the ability to change data
's content from outside DataViewModel
class could make it harder to debug and reason about where data
's content is coming from at any given time.