Skip to content

Instantly share code, notes, and snippets.

@fvilarino
Last active May 25, 2021 20:51
Show Gist options
  • Save fvilarino/4bae6324310443d90040d2e54264b849 to your computer and use it in GitHub Desktop.
Save fvilarino/4bae6324310443d90040d2e54264b849 to your computer and use it in GitHub Desktop.
Compose ViewModel LIfecycle
@HiltViewModel
class CityViewModel @Inject constructor() : ViewModel() {
fun onStart() {
// start task - the composable has entered the composition
}
fun onStop() {
// cancel task - the composable has left the composition
}
}
@Composable
fun CityScreen(
viewModel: CityViewModel,
modifier: Modifier = Modifier,
) {
val state = viewModel.state.collectAsState()
DisposableEffect(key1 = viewModel) {
viewModel.onStart()
onDispose { viewModel.onStop() }
}
// screen content omitted for brevity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment