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

Time:07-22

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).

CodePudding user response:

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

CodePudding user response:

Since you are using mutableState you can use recommended method by as follows

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

then

fun checkAvailability() = viewModelScope.launch {
    repository.checkAvailability().collect { response ->
        isAvailableState = response //isAvailableState.copy(response= response)
    }
}

check https://developer.android.com/jetpack/compose/state#viewmodels-source-of-truth for more details

CodePudding user response:

You can do it by changing visibility of setter of isAvailable to private

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

this is how you set it but as Ardian mentioned you pass value not the state itself.

You can do it by creating a function inside ViewModel such as

fun isAvailable(): State<Response<Boolean> = isAvailable as State<Boolean>

but both answers still require a method for setting value of MutableState

  • Related