0

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

Joan P.
  • 2,368
  • 6
  • 30
  • 63

2 Answers2

3

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

Adrian K
  • 3,942
  • 12
  • 15
  • Thanks for taking the time to answer my question. Are there any downsides if I read the value very early? Voted-up. – Joan P. Jul 22 '22 at 10:02
2

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

masokaya
  • 589
  • 4
  • 10
  • So to understand better, `isAvailableState = response` is equivalent with `isAvailableState.copy(response= response)`, right? Voted-up. – Joan P. Jul 22 '22 at 10:03