【问题标题】:Is there a better way to expose private MutableLiveData as LiveData for an ViewModel. [Android, Kotlin]有没有更好的方法将私有 MutableLiveData 公开为 ViewModel 的 LiveData。 [安卓、科特林]
【发布时间】:2020-07-17 11:01:38
【问题描述】:

在下面的示例中,我想像这样公开一个 Int 列表:

    val test: LiveData<List<Int>>
        get() = _test as LiveData<List<Int>>

    private var _test = MutableLiveData(mutableListOf<Int>())

或者换一种说法:

    private var _test2 = MutableLiveData(mutableListOf<Int>())
    val test2 = _test2 as LiveData<List<Int>>

两者都在工作,但总是有未经检查的演员表。

Unchecked cast: MutableLiveData<MutableList<Int>!> to LiveData<List<Int>>

有更好的方法吗?


澄清一下:

通过使用emptyList,用法可能如下所示:

class MainViewModel : ViewModel() {
    val test: LiveData<List<Int>> get() = _test
    private var _test = MutableLiveData(emptyList<Int>())

    init {
        val myPrivateList = mutableListOf<Int>()
        myPrivateList.add(10)
        myPrivateList.add(20)

        _test.value = myPrivateList
    }
}

我希望找到一种无需额外列表 (myPrivateList) 的方法,如下所示:

class MainViewModel : ViewModel() {
    val test: LiveData<List<Int>> get() = _test
    private var _test = MutableLiveData(emptyList<Int>())

    init {
        _test.value?.apply {
            add(1)
            add(2)
            add(3)
        }
    }
}

【问题讨论】:

    标签: android kotlin mvvm android-livedata mutablelivedata


    【解决方案1】:

    您可以使用 emptyList&lt;Int&gt;()listOf&lt;Int&gt;() 创建 MutableLiveData 避免未经检查的演员表:

    val test: LiveData<List<Int>> get() = _test
    private var _test = MutableLiveData(emptyList<Int>())
    

    如果您的代码只是您真实用例的一个示例,请记住您始终可以在您的 MutableList 上使用 .toList()

    【讨论】:

    • 谢谢。基本上 _test 成为与 test -> LiveData> 相同的类型我希望在没有“额外”列表(myPrivateList)的情况下解决它。
    猜你喜欢
    • 2023-03-31
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2022-07-22
    • 2022-12-28
    • 1970-01-01
    相关资源
    最近更新 更多