I am stuck in Android compose StateFlow. I have a project in XML and I am converting it to compose. I want to show a composable dialog from an activity using state in ViewModel. On API success I am updating the state of the dialog which is collectAsState in activity, but I couldn't open the dialog from activity.
ViewModel code
private val _state: MutableStateFlow<GenericDialogState> =
MutableStateFlow(GenericDialogState())
val state: StateFlow<GenericDialogState>
get() = _state.asStateFlow()
_state.update { _state.value.copy(showDialog = true) } //On API response
MyActivity Code: (How to cause compose function here or how to define state for composable function)
lifecycleScope.launch(Dispatchers.Main) {
repeatOnLifecycle(state = Lifecycle.State.STARTED) {
mainActivityViewModel.state.collect { uiState ->
// New value received
if (uiState.showDialog)
Log.i(uiState.toString(), uiState.showDialog.toString())
// ComposeGenericDialog(myParameter = MyParameter())
}
}
}
Please rectify if I am wrong
data class GenericDialogState(
var showDialog: Boolean = false
)
You can make a
SharedFlowobject inViewModeland update its value when you complete an API call or other operation.On The UI side, you need to collect
SharedFlowand when the value satisfies the condition it will showDialogOrToast.