androidkotlinandroid-jetpack-composekotlin-stateflow

How do I update the collection correctly to update StateFlow?


In my application, when updating the map StateFlow is not updated. Help me update StateFlow correctly.

data class PageData(val selectedCheckbox: Int, val enable: Boolean)

@HiltViewModel
internal class QwizViewModel @Inject constructor(private val navigationManager: NavigationManager) :
    FeatureViewModel<QwizContract.Event, QwizContract.State, QwizContract.Effect>() {

    private val _mapStateFlow = MutableStateFlow<MutableMap<Int, PageData>>(mutableMapOf())
    val mapStateFlow = _mapStateFlow.asStateFlow()

 private fun onEventSelected(event: QwizContract.Event.ActionsEvent) {
        when (event) {
            is QwizContract.Event.ActionsEvent.SelectAnswer -> {
                _mapStateFlow.value[event.currentPage] = PageData(selectedCheckbox = event.selectedCheckbox, enable = event.enabledBtn)
            }
        }
    }
}

accessing stateflow on screen

val mapState by vm.mapStateFlow.collectAsState()

LaunchedEffect(mapState) {
    selectedIndex = mapState.takeIf { it.isNotEmpty() }?.get(currentPage)?.selectedCheckbox ?: -1
}

Solution

  • fun addItem(page: Int, newItem: PageData) {
        val currentItems = _mapStateFlow.value.toMutableMap()
        currentItems[page] = newItem
        _mapStateFlow.value = currentItems
    }
    
    fun addItem(page: Int, newItem: PageData) {
        _mapStateFlow.update { currentMap ->
            currentMap.toMutableMap().apply { this[page] = newItem }
        }
    }