Home > Software engineering >  Update of StateFlow not propagating to the Jetpack Compose UI
Update of StateFlow not propagating to the Jetpack Compose UI

Time:01-15

I'm trying Jetpack Compose on Android with a viewmodel and StateFlow on a super small game application, and I've followed the codelabs, but when I update my state, nothing happens on the UI. I'm sure I'm missing something stupid, but I'm unable to see it. Here's my code inside the view model:

    private val _uiState = MutableStateFlow(HomeScreenState())
    val uiState = _uiState.asStateFlow()

...

    private fun popLists() {
        uiState.value.apply {
            currentLetters = lettersList.pop()
            where = wordPartsList.pop()
        }
    }

in the screen of the app I do

        val gameUiState by viewModel.uiState.collectAsState()

and then in the composition

        BombDisplay(gameUiState.currentLetters, context)

BombDisplay is a simple custom composable with a Text with predetermined style and a background. The "HomeScreenState" is also a simple data class with a couple of Strings in it.

There's also a button that when pressed calls a public method from the viewmodel that calls the "popList" function. I followed the entire thing with the debugger and it all actually works, but the UI seems unaware of the changes to the data.

I've retraced all the steps from varius codelabs and tutorials, but I don't get where the mistake is.

CodePudding user response:

The problem is in the popLists method. Instead of updating the old value u should pass the new value, smth like:

private fun popLists() {
    val newState = uiState.value.copy(
        currentLetters = lettersList.pop(),
        where = wordPartsList.pop()
    )
    uiState.value = newState
}
  • Related