Skip to content

Instantly share code, notes, and snippets.

@saqib-github-commits
Created June 11, 2023 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saqib-github-commits/6b6fcae2378f7a38fe6fb7b78c02a712 to your computer and use it in GitHub Desktop.
Save saqib-github-commits/6b6fcae2378f7a38fe6fb7b78c02a712 to your computer and use it in GitHub Desktop.
@Composable
fun DisposableEffectWithLifecycle(
onCreate: () -> Unit = {},
onStart: () -> Unit = {},
onStop: () -> Unit = {},
onResume: () -> Unit = {},
onPause: () -> Unit = {},
onDestroy: () -> Unit = {},
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
) {
val currentOnCreate by rememberUpdatedState(onCreate)
val currentOnStart by rememberUpdatedState(onStart)
val currentOnStop by rememberUpdatedState(onStop)
val currentOnResume by rememberUpdatedState(onResume)
val currentOnPause by rememberUpdatedState(onPause)
val currentOnDestroy by rememberUpdatedState(onDestroy)
DisposableEffect(lifecycleOwner) {
val lifecycleEventObserver = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> currentOnCreate()
Lifecycle.Event.ON_START -> currentOnStart()
Lifecycle.Event.ON_PAUSE -> currentOnPause()
Lifecycle.Event.ON_RESUME -> currentOnResume()
Lifecycle.Event.ON_STOP -> currentOnStop()
Lifecycle.Event.ON_DESTROY -> currentOnDestroy()
else -> {}
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleEventObserver)
onDispose {
lifecycleOwner.lifecycle.removeObserver(lifecycleEventObserver)
}
}
}
// News Screen
@Composable
fun NewsScreenWithDisposableEffectLifecycle(viewModel: NewsViewModel = NewsViewModel()) {
DisposableEffectWithLifecycle(
onResume = { viewModel.fetchNews() }
)
// list of news
LazyColumn {
// list of news
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment