我使用ViewModel来获取设置片段所需的数据。当我调用get viewModel.getItems()。observer {}时,它总是返回一个空列表,除非我更改设备方向或暂停并恢复片段。
class OnSaleListFragmentViewModel : ViewModel() {
private val items : MutableLiveData<List<Item>> by lazy {
MutableLiveData<List<Item>>().also {
loadItems()
}
}
private fun loadItems() {
viewModelScope.launch {
getDataFromDAO()
}
}
fun getItems() : LiveData<List<Item>> {
return items
}
private suspend fun getDataFromDAO() = withContext(Dispatchers.IO) {
val dao : DAO = DAO.instance
val data = async { dao.getItems() }
try {
items.postValue(data.await())
} catch (e : Exception) {
items.postValue(listOf())
}
}
尝试替换
private val items : MutableLiveData<List<Item>> by lazy {
MutableLiveData<List<Item>>().also {
loadItems()
}
}
与
private val items = MutableLiveData<List<Item>>()
并从其他地方呼叫loadItems()