What is the recommended way to attach a Composable to a StateFlow from a ViewModel?
I have a ViewModel which exposes an alert dialog state:
data class NameDialogState(val show: Boolean, val nameFieldValue: TextFieldValue)
val nameDialogState: StateFlow<NameDialogState>
The composable has a parameter for its UI state:
@Composable
fun NameDialog(uiState: State<NameDialogState>) {
if (uiState.value.show) {
AlertDialog(
// ...
text = TextField(value = uiState.value.nameFieldValue)
)
// ...
}
}
Inside the Fragment, the composable for the dialog takes the flow with
collectAsState()
val uiState = viewModel.nameDialogState.collectAsState()
setContent {
NameDialog(uiState = uiState)
}
This works, but I wonder if it is possible to get rid of the
State<*>
in the composable and use
NameDialogState
directly, like this:
@Composable
fun NameDialog(uiState: NameDialogState)
All Google examples recommend injecting viewmodel directly into composable, which doesn't seem good architecture... I would like to keep the composables as "stupid" as possible.