ViewModel backing properties [kotlin]
Asked Answered
D

1

9

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?

Dustin answered 29/10, 2018 at 16:51 Comment(0)
B
7

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.

Breakfast answered 29/10, 2018 at 21:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.