MutableState in view model?

Viewed 4997

In all the examples I have seen with view models in combination with Jetpack Compose, one usually stores a state in the view model as MutableStateFlow and then applies collectAsState in the compose function in order to get a Compose state.

My question: Why not store the state directly in the view model, and not some flow? E.g.

class MyViewModel: ViewModel() {
    val showDialog = mutableStateOf(false)
}

@Compose
fun MyScreen(viewModel: MyViewModel) {
    Button(onClick = { viewModel.showDialog = true })
    if (viewModel.showDialog) {
        AlertDialog(...)
    }
}

The above code seems to run as intended. Is this a valid solution then?

2 Answers

Yes it certainly is. I don't know where you saw those examples, but this is indeed the recommended practice. You can check the State Codelab; it demonstrates how to replace the LiveData objects to mutableStateOf inside the viewmodel. Also, as far as the usage of LiveData and Flow is concerned, it is mainly for interoperability, as far as I know. The apps which are not fully built in Compose, but are being transferred, or apps which plan to use the view system alongside Compose. mutableStateOf is only for Jetpack compose and hence, developers will want to use LiveData in such cases. However, if you are building a brand new project, and want it to be composed of only Compose, then definitely go for what you've mentioned in the question. It is the correct way.

Flow comes from kotlinx.coroutines it's used to observe async changes, while State is for updating compose UI changes. You're to use Flow regardless of UI if you're following subscribe to stream for changes pattern. Again, you can follow some complicated/incomplete pattern, but why would you?

Related