I don't quite understand the behavior of MutableLiveData or I can't find the proper documentation.
But I need help.
_series.value = _series.value?.plus(it) // ??? 11111111
_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
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
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
val liveDataSeries =
if (_series.value == null) emptyList<Serie>() // set the array list to empty if _series.value is null
else ArrayList(_series.value) // else: add _series.value elements to the array list
series?.forEach {
liveDataSeries.add(it) // add each serie to the array list
}
_series.value = liveDataSeries // update _series.value
} catch (e: Exception) {
Log.d(TAG, "fetchSeries: ${e.message}")
}
}
}
fun clearDb() = viewModelScope.launch {
database.clear()
_series.value = emptyList()
}
}