ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-11-10 15:33:52  阅读:272  来源: 互联网

标签:kotlin android-viewmodel android


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有