I'm working on a stateful Jetpack Compose composable that follows the MVI architecture. I'm using collectAsStateWithLifecycle() to observe the view state from a view model, but I'm unsure about the best approach to collect side effects with lifecycle awareness.
I'd appreciate your insights on:
The correctness of the current approach.
Potential improvements or alternative techniques.
Best practices for collecting viewstate and side effects with lifecycle awareness in Jetpack Compose.
@Composable
fun CountryListScreenContent(callback: (countryName: String) -> Unit) {
val viewModel: CountryListViewModel = hiltViewModel()
val countryListViewState by viewModel.viewState.collectAsStateWithLifecycle()
LaunchedEffect(Unit) {
viewModel.sideEffect.collect {
if (it is CountryListContract.SideEffect.NavigateToDetails) {
val countryName = it.countryName
callback(countryName)
}
}
}
CountryListViewState(viewState = countryListViewState, callback = { it ->
viewModel.sendIntent(
...
)
})
}
CountryListViewModel
itself have any access to a CoroutineScope? How do you create it? What does the callback do? It looks a bit to me like the callback-related code belongs in the viewmodel instead of in your compose code. \$\endgroup\$