In the following example I want to expose a List of Int like this:
val test: LiveData<List<Int>>
get() = _test as LiveData<List<Int>>
private var _test = MutableLiveData(mutableListOf<Int>())
or in another flavor:
private var _test2 = MutableLiveData(mutableListOf<Int>())
val test2 = _test2 as LiveData<List<Int>>
Both are working, but there is always an Unchecked Cast.
Unchecked cast: MutableLiveData<MutableList<Int>!> to LiveData<List<Int>>
Is there a better way of doing this?
Just to clarify:
By using emptyList the usage could look like this:
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
}
}
I was hoping to find a way to do this without an extra list (myPrivateList), something like this:
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)
}
}
}
> I was hoping to solve it without an "extra" list (myPrivateList).
– Awa Kenzo Apr 05 '20 at 18:08