I want to update the data in the database and display the updated data on the screen.But I can't do it. The update occurs only after restarting the application. What am I doing wrong?. Help please
fun list(model: MyViewModel = viewModel()) {
val list = model.listToDo.observeAsState(listOf()).value
val grouped = list.groupBy { it.isFinished }
LazyColumn(contentPadding = PaddingValues(vertical = 8.dp)
, verticalArrangement = Arrangement.spacedBy(8.dp)
, ){
grouped.forEach { (initial, contactsForInitial) ->
stickyHeader {
Text(
"Section $initial",
Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
items(contactsForInitial) { contact ->
card(contact, model = model)
}
}
}
}
Function in viewmodel
fun update(task: ToDo){
viewModelScope.launch(Dispatchers.IO) {
repository.update(task)
}
}
Function in the dao
@Update
fun update(task: ToDo)
ViewModel
class MyViewModel : ViewModel() {
private val repository = Repository.get()
val listToDo = repository.getListToDo()
fun delete(task: ToDo){
viewModelScope.launch(Dispatchers.IO) {
repository.delete(task)
}
}
fun insertToDo(task: ToDo){
repository.insertToDo(task = task)
}
fun update(task: ToDo){
viewModelScope.launch(Dispatchers.IO) {
repository.update(task)
}
}}
CodePudding user response:
You are not observing the state. I think this code:
val list = model.listToDo.observeAsState(listOf()).value
just takes a single snapshot of the flow. Try it like that:
val list by model.listToDo.observeAsState(listOf())