For example, I have this simple Composable function
@Composable
fun TextExample(model: SomeViewModel = viewModel()) {
TextButton(onClick = { model.onClick() }) {
Text(text = "Test")
}
}
The SomeViewModel:
class SomeViewModel : ViewModel() {
private val _text = mutableStateOf("Test")
val text: String
get() = _text.value
fun onClick() {
if (text.isEmpty()) {
// TODO: need to start some activity
} else {
_text.value = ""
}
}
}
I clicking this Button and then the model must to handle this click. In some cases I need to start another activity. What is right way to do this?
There might better approach to this but you can consider mine.
Id suggest first to create a data structure for "one time events" with a
Sealed Classlike thisDeclare a
SharedFlowin your ViewModel that will emit these eventsand in your case, emit an event from your onClick viewmodel function like this
Now in your composable, just observe it in a
LaunchedEffectlike thisIf you don't have something prepared yet for calling startActivity, I'd suggest visiting this post as a reference.