Compose mutableStateFlow is not trigger ui update

38 views Asked by At

I have a mutableStateFlow that represents the state of my view in the viewmodel. That state is composed of a list of People that have a background color property. The task is to assign the same background color to all people but assign said color 1 at a time. Example we update color for person1, then we update color for person2... The result I get is that only the first element in the view is updated, all other updates will be done correctly at the viewmodel level but are not reflected in the view. If i remove de delay on the flow the view update too quickly and i need a delay bettwen each color change.

data class Person(val name: String, val color: String)

data class PersonViewState(val list: List<Person> = listOf(....))

class PersonViewModel() : ViewModel() {

    private val _state = MutableStateFlow(PersonViewState())
    val state = _state.asStateFlow()

    fun changeAllColor() {
        viewModelScope.launch {
            val personFLow = state.value.list.toMutableList().asFlow()
            personFLow
                .onEach { delay(2000) } 
                .collectIndexed { index, value ->
                val personCopy = state.value.list.toMutableList()
                personCopy[index] = value.copy(color = "#000000")
                _state.update { it.copy(list = personCopy) }
            }
        }
    }
}
0

There are 0 answers