Reputation: 449
Looking to the code of some Google's demo app (like sunflower or Google io 2018 app) and I've noticed that for the viemodels' backing properties they use a separate instance of the same type with a custom getter; like this:
private val _userData: MutableLiveData<User>
val userData: LiveData<User>
get() = _userData
but why do they do that? Isn't better to directly make the _userData
accessible?
Could it be because while _userData
is a MutableLiveData
they don't want the observer to be able to change the value?
Upvotes: 9
Views: 1729
Reputation: 8916
userData
which is exposed to the Activity or Fragment must be immutable since the view only needs to observe to the LiveData
. So, we need to make the actual _userData
returns a LiveData
.
One way is using the Kotlin coding convention and create two variables, _userData
and userData
, one is mutable and another one is not:
If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property.
Upvotes: 7