I'm trying to update a parameter of my Model. I have a MutableStateFlow with a list with some of my model created.
data class MyModel(
val id: Int,
val category: String,
var completed: Boolean
)
val listOfModel = listOf(
MyModel(
id = 0,
category = "shopping",
completed = true
), MyModel(
id = 1,
category = "web",
completed = false
)
)
var _modelStateFlow = MutableStateFlow(listOfModel)
var modelStateFlow = _modelStateFlow.asStateFlow()
What I want to do in my other class, is to update the "completed" parameter in the model. That's what I tried but I get the following error:
Type mismatch. Required: List<"MyModel"> Found: MyModel
_modelStateFlow.update { it[current.value!!].copy(completed = !modelStateFlow.value[current.value!!].completed) }
CodePudding user response:
You can do it like this:
_modelStateFlow.update { list ->
list.mapIndexed { index, myModel ->
if(index == indexToUpdate) myModel.copy(completed = !myModel.completed)
else myModel
}
}
The reason you are getting that error is because, you need to return a new list inside update
function which represents the new value of StateFlow
. You can create that new list using map
function. Update the model at the desired index keeping others as they are.