Kotlin ViewModel StateFlow - Properly Updating State Changes
21:04 09 Jun 2026

This question is to understand StateFlow in a view-model. How to update the value more than one time properly. So, a very interesting issue happens, value updates for this first time, when, say authV1 is called, but it does not update when authV2 is called, or reset is called. How to ensure the state is copied properly to ensure the state-flow gets updated, and view shows the latest values. (please note, the view itself simply shows a column with a text view for value, and buttons to update the value)

class AuthViewModel: ViewModel() { // transient value/state
    
    private val _authEntityMutableStateFlow = MutableStateFlow(AuthEntity(token = ""))
    val authEntityStateFlow = _authEntityMutableStateFlow.asStateFlow()

    fun update(data: AuthEntity) {
        // required in kotlin because it does not update by value
        _authEntityMutableStateFlow.value = _authEntityMutableStateFlow.value.copy(auth = data.auth) // or authEntityStateFlow
    }

    fun authV1() {
        viewModelScope.launch {
            update(AuthRepo.instance.getTestTokenV1()) // this method uses suspend call withContext
        }
    }

    fun authV2() {
        viewModelScope.launch {
            AuthRepo.instance.getTestTokenV2() // this method uses return withContext(Dispatchers.IO) { Result.success for testing with fixed value
                .onSuccess { authRespEntity ->
                    update(authRespEntity.data)
                }
        }
    }

    fun reset() {
        update(AuthEntity(token = ""))
    }
}

@Composable
fun AuthScreen(authViewModel: AuthViewModel = AuthViewModel()) {
    val authEntityStateFlow = authViewModel.authEntityStateFlow.collectAsStateWithLifecycle()
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text("authEntityStateFlow: ${authEntityStateFlow.value}")
        Button(onClick =  {
            authViewModel.authV1()
        }) {
            Text("authV1")
        }
        Button(onClick =  {
            authViewModel.authV2()
        }) {
            Text("authV2")
        }
        Button(onClick =  {
            authViewModel.reset()
        }) {
            Text("reset")
        }
    }
}
kotlin android-jetpack-compose kotlin-stateflow