I have been having trouble updating my activity/UI layer from my viewModel()
reliably when I change the value of a field in an object I am using to show a download progress bar. The activity observes the adding and removal of objects from the list fine, but not changes to the progress field.
Data Class
data class DownloadObject(
val id: String?,
var progress: Float,
)
ViewModel
class MyViewModel () : ViewModel() {
private val _progressList = MutableStateFlow<List<DownloadObject>>(emptyList())
val progressList: StateFlow<List<DownloadObject>>
get() = _progressList
//add to list updates the activity
_progressList.value += DownloadObject
//remove from list updates the activity
_progessList.value -= DownloadObject
// Change progress field doesn't update the activity
_progressList.value.onEach{
if(it.id == id) {it.progress = progress}
}
}
Activity
val progressList by courseViewModel.progressList.collectAsState(emptyList()
...
LinearProgressIndicator(progress = progressList.find { it.id == id }?.progress)
I've tried using mutableStateListOf()
and MutableLiveData
but face many of the same issues. I've taken both the state codelabs for compose and am really not sure what to do from here. Would appreciate any help, thanks!
// Change progress field doesn't update the activity
_progressList.value.onEach{
if(it.id == id) {it.progress = progress}
}
This doesn't actually trigger an update in your progressList
StateFlow
.
To do that you'd probably want use something like this:
_progressList.value = progressList.value.map {
if(it.id == id) {
it.copy(progress = progress)
} else {
it
}
}