Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel backing properties [kotlin]

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?

like image 842
Andrea Avatar asked Oct 29 '18 16:10

Andrea


People also ask

What is backing properties in Kotlin?

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.

What are Kotlin's 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.

How does ViewModel retain data?

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.

What is use of backing field?

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.


1 Answers

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.

like image 98
Saeed Masoumi Avatar answered Oct 04 '22 22:10

Saeed Masoumi