是否有更好的方法将私有 MutableLiveData 公开为 ViewModel 的 LiveData。[安卓、科特林]

1 android mvvm kotlin android-livedata mutablelivedata

在以下示例中,我想公开这样的 Int 列表:

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

    private var _test = MutableLiveData(mutableListOf<Int>())
Run Code Online (Sandbox Code Playgroud)

或另一种口味:

    private var _test2 = MutableLiveData(mutableListOf<Int>())
    val test2 = _test2 as LiveData<List<Int>>
Run Code Online (Sandbox Code Playgroud)

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

Unchecked cast: MutableLiveData<MutableList<Int>!> to LiveData<List<Int>>
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点?


只是为了澄清:

通过使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望找到一种无需额外列表(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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gio*_*oli 5

您可以使用emptyList<Int>()listOf<Int>()来创建MutableLiveData避免未经检查的演员表:

val test: LiveData<List<Int>> get() = _test
private var _test = MutableLiveData(emptyList<Int>())
Run Code Online (Sandbox Code Playgroud)

如果您的代码只是您实际用例的示例,请记住您始终可以.toList()MutableList.