ViewModel 支持属性 [kotlin]
ViewModel backing properties [kotlin]
查看某些 Google 的演示应用程序(如向日葵或 Google io 2018 应用程序)的代码,我注意到对于 viemodels 的支持属性,他们使用一个单独的实例与自定义相同类型 getter;像这样:
private val _userData: MutableLiveData<User>
val userData: LiveData<User>
get() = _userData
但他们为什么要那样做?直接使 _userData
可访问不是更好吗?
可能是因为 _userData
是 MutableLiveData
他们不希望观察者能够更改值?
暴露给 Activity 或 Fragment 的 userData
必须是不可变的,因为视图只需要观察到 LiveData
。所以,我们需要把实际的_userData
returns变成LiveData
。
一种方法是使用 Kotlin coding convention 并创建两个变量,_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.
查看某些 Google 的演示应用程序(如向日葵或 Google io 2018 应用程序)的代码,我注意到对于 viemodels 的支持属性,他们使用一个单独的实例与自定义相同类型 getter;像这样:
private val _userData: MutableLiveData<User>
val userData: LiveData<User>
get() = _userData
但他们为什么要那样做?直接使 _userData
可访问不是更好吗?
可能是因为 _userData
是 MutableLiveData
他们不希望观察者能够更改值?
userData
必须是不可变的,因为视图只需要观察到 LiveData
。所以,我们需要把实际的_userData
returns变成LiveData
。
一种方法是使用 Kotlin coding convention 并创建两个变量,_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.