[英]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;查看一些 Google 演示应用程序(如向日葵或 Google io 2018 应用程序)的代码,我注意到对于 viemodels 的支持属性,它们使用具有自定义 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?直接使
_userData
可访问不是更好吗? Could it be because while _userData
is a MutableLiveData
they don't want the observer to be able to change the value?可能是因为虽然
_userData
是MutableLiveData
他们不希望观察者能够更改值?
userData
which is exposed to the Activity or Fragment must be immutable since the view only needs to observe to the LiveData
.暴露给 Activity 或 Fragment 的
userData
必须是不可变的,因为视图只需要观察LiveData
。 So, we need to make the actual _userData
returns a LiveData
.所以,我们需要让实际的
_userData
返回一个LiveData
。
One way is using the Kotlin coding convention and create two variables, _userData
and userData
, one is mutable and another one is not:一种方法是使用Kotlin 编码约定并创建两个变量,
_userData
和userData
,一个是可变的,另一个不是:
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.
如果一个类有两个概念上相同的属性,但一个是公共 API 的一部分,另一个是实现细节,请使用下划线作为私有属性名称的前缀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.