android-Kotlin:不可变类型对可变类型内部变量的只读访问
作者:互联网
在Android中学习ViewModels时,出现了一个问题,感觉像是要解决Kotlin.在下面的代码中,我们可以看到MutableLiveData值正在用于编辑值和指标.但是,我们不希望这些可变值暴露给其他任何事物,特别是Android生命周期的成员.我们确实希望Android Lifecycle成员有权读取值,但不能设置它们.因此,下面显示的3个公开功能是LiveData的功能.不变类型.
有没有更简单或更简洁的方法来公开可以在内部编辑的只读值?这似乎是Kotlin要避免的事情:样板冗长.
class HomeListViewModel: ViewModel(){
//Private mutable data
private val repositories = MutableLiveData<List<Repo>>()
private val repoLoadError = MutableLiveData<Boolean>()
private val loading = MutableLiveData<Boolean>()
//Exposed uneditable LIveData
fun getRepositories():LiveData<List<Repo>> = repositories
fun getLoadError(): LiveData<Boolean> = repoLoadError
fun getLoadingStatuses(): LiveData<Boolean> = loading
init{...//Do some stuff to MutableLiveData<>
}
}
可能类似的非Android场景是:
class ImmutableAccessExample{
private val theThingToBeEditedInternally = mutableListOf<String>()
fun theThingToBeAccessedPublicly(): List<String> = theThingToBeEditedInternally
init {
theThingToBeEditedInternally.add(0, "something")
}
}
解决方法:
我不知道是否有可能避免冗长.但是,我之前已经看到过,通常将其声明为属性.
private val _repositories = MutableLiveData<List<Repo>>()
val repositories : LiveData<List<Repo>>
get() = _repositories
这是约定,请参阅名称中的the doc here作为后备属性
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:
标签:kotlin,android-viewmodel,android 来源: https://codeday.me/bug/20191110/2013459.html