Search code examples
androidkotlinviewmodelkotlin-flow

Viewmodel executes init after updating a MutableStateFlow


whenever I try to update a mutable state flow (uiState), the code in the init of the viewModel executes again (and hence the uiState resets).

This only happens if I use any info related to the previous state of the uiState (at least that's why I think given the following code).

The Code:

init {
        Log.d("Error log", "init again")
    }

    private val _uiState: MutableStateFlow<CreateGameState> =
        MutableStateFlow(
            CreateGameState.InputDataState(
                selectedHeroes = listOf(),
                selectedVillain = null,
                selectedEncounters = listOf(),
            )
        )
    val uiState: StateFlow<CreateGameState> = _uiState

    fun onAction(action: CreateGameActions) {
        when (action) {
            is CreateGameActions.SelectHero -> {
                when (_uiState.value) {
                    is CreateGameState.InputDataState -> {
                        _uiState.update {
                            /* this line causes the error */(it as CreateGameState.InputDataState).copy(selectedHeroes = it.selectedHeroes.plusElement(action.hero))
                         /* this line doesn't cause error */(it as CreateGameState.InputDataState).copy(selectedHeroes = listOf(Hero.SPIDERMAN))
                        }
                    }
                }
            }
        }
    }
}

So when only executing the line that causes the error, the Log of the init function is shown in Logcat again. With this, I loose the uiState and my app gets stuck on the initial state always.

Thanks a lot for your help in advance!


Solution

  • @Tenfour04 was right. I turns out I was injecting the viewModel in a composable with the constructor as a default parameter. Recomposition was causing the creation of a new ViewModel.

    Simply by injecting the same instance of the viewModel solved it.