Search code examples
androidkotlinandroid-jetpack-composekotlin-coroutineskotlin-stateflow

How to change the value of state object without using _?


In my app I perform a request to an API that should return a boolean. Inside the ViewModel class I have these 2 objects:

private val _isAvailableState = mutableStateOf<Response<Boolean>>(Success(false))
val isAvailableState: State<Response<Boolean>> = _isAvailableState

One is mutable and the other one isn't. Here is how I read the value:

fun checkAvailability() = viewModelScope.launch {
    repository.checkAvailability().collect { response ->
        _isAvailableState.value = response
    }
}

Is there any way in which I can change the value without using this solution? I hate using _ (underscore).


Solution

  • So only other solution here would be using the delegation syntax of MutableState and making only the setter private. However this also implies that you are no longer able to pass around the state object, but instead are forced to read the value very early.

    var isAvailableState by mutableStateOf<Response<Boolean>>(Success(false))
        private set
    

    Now your able to call isAvailableState = response from inside your ViewModel , but from your Composable's perspective, the field is read-only