mutableLivedata,livedata列表为空或添加项目第一个位置
我不太了解mutablelivedata的行为,或者找不到适当的文档。
但是我需要帮助。
- 我需要在数组的第一个位置添加一个元素,并尝试使用“ Plus”尝试,但它无法正常工作。还是有一种方法可以在第一个位置添加数组的多个元素?
_series.value = _series.value?.plus(it)// ??? 11111111
- 我不知道如何删除数组的所有元素,我用
_series.value = null //? 2222222
_series.value = arraylist()/// ??? 2222222
,但我认为这不是最好的方法。
class SerieViewModel(val database: SerieDatabaseDao) : ViewModel() {
private val _series = MutableLiveData<List<Serie>?>()
val series: LiveData<List<Serie>?>
get() = _series
fun fetchSeries(code: String) {
viewModelScope.launch {
try {
val response = CodesApi.retrofitService.getSeries(code)
val series = response.body()?.data
series?.forEach {
_series.value = _series.value?.plus(it) // ??? 11111111
}
}
} catch (e: Exception) {
Log.d(TAG, "fetchSeries: ${e.message}")
}
}
}
fun clearDb() = viewModelScope.launch {
database.clear()
_series.value = null // ??? 2222222
_series.value = ArrayList<Serie>() /// ??? 2222222
}
谢谢
I don't quite understand the behavior of MutableLiveData or I can't find the proper documentation.
But I need help.
- I need to add an element to the first position of the array and tried with "plus" but it doesn't work properly. Or is there a way to add multiple elements of an array in the first position?
_series.value = _series.value?.plus(it) // ??? 11111111
- I can't figure out how to delete all the elements of the array, I did it with
_series.value = null // ??? 2222222
_series.value = ArrayList() /// ??? 2222222
but I don't think it is the best way to do it.
class SerieViewModel(val database: SerieDatabaseDao) : ViewModel() {
private val _series = MutableLiveData<List<Serie>?>()
val series: LiveData<List<Serie>?>
get() = _series
fun fetchSeries(code: String) {
viewModelScope.launch {
try {
val response = CodesApi.retrofitService.getSeries(code)
val series = response.body()?.data
series?.forEach {
_series.value = _series.value?.plus(it) // ??? 11111111
}
}
} catch (e: Exception) {
Log.d(TAG, "fetchSeries: ${e.message}")
}
}
}
fun clearDb() = viewModelScope.launch {
database.clear()
_series.value = null // ??? 2222222
_series.value = ArrayList<Serie>() /// ??? 2222222
}
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在存储列表&lt; serie?&gt;这很好,这是您应该做的,但是您不能将元素添加到列表中,您需要将列表转换为arrayList并将元素添加到ArrayList中,而不是更新MutableLiveData,请按照下面的代码。
。
要清除列表中的所有元素,您可以将值设置为fermylist(),请按照下面的代码。
。
注意:查看列表,arraylist,array in kotlin中的差异,它们不是相同的
You are storing a List<Serie?> which is fine thats what you should do, but you can't add elements to List, you need to convert List to ArrayList and add elements to the ArrayList than update the MutableLiveData, follow the code below.
to clear all the elements from the List you can set the value to emptyList(), follow the code below.
Note: Take a look about the difference between List, ArrayList, Array in kotlin they are not the same