android - Kotlin:不可变类型对可变类型的内部变量的只读访问

标签 android kotlin android-viewmodel

在学习 Android 中的 ViewModel 时,出现了一个感觉 Kotlin 旨在解决的问题。在下面的代码中,我们可以看到 MutableLiveData 值被用于编辑值和指标。但是,我们不希望这些可变值暴露给其他任何东西,特别是 Android 生命周期的成员。我们确实希望 Android 生命周期成员有权访问读取值但不能设置它们。因此,下面显示的 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:

关于android - Kotlin:不可变类型对可变类型的内部变量的只读访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405101/

相关文章:

android - 由于依赖性冲突,无法完成安装。开发工具包 23.0

android - 如何在android中点击覆盖时显示弹出窗口?

kotlin - Kotlin 是否允许您为枚举分配自定义值?

android - 将 LiveData 更改为 "redo"在 ViewModel 中工作

android - ViewModelFactory can't create an instance 错误创建自定义ViewModelFactory类

android - 如何确定哪个 android 市场用于下载我的应用程序

android - Android 上的 SVG 支持,当前状态

android - 如何通过改造解析 JSON 响应

unit-testing - 使用 PowerMock 在 Kotlin 中模拟包级函数

android - 如何在一组特定 fragment 之间共享 ViewModel 范围,而不使用 NavGraphs 或将其范围限定到 Activity ?