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?
If you need to access a field of a property inside a class in which it's declared, you can use backing properties. If you only need to access a field from the getter or setter of its property, it's enough to use backing fields. However, if you want to access a field somewhere else, you should use backing properties.
Variable having a class level scope (member variables) which are declared inside the class but outside the methods or functions is called as Property in Kotlin. They are declared with var keyword for a mutable one and with val keyword for a read-only/nonmutable one. The initializer, getter and setter are optional.
ViewModel objects are automatically retained (they are not destroyed like the activity or a fragment instance) during configuration changes so that data they hold is immediately available to the next activity or fragment instance.
Moreover, we can reference the backing field inside custom accessors via the field identifier. Put simply, the backing field is where the value for a property will be stored. In the last example, the backing field helped us to avoid the recursion issue.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With