Skip to content

Instantly share code, notes, and snippets.

@vitoksmile
Created March 3, 2025 16:10
Show Gist options
  • Save vitoksmile/8ec271692b7c5b6c4e415ebb6914ba97 to your computer and use it in GitHub Desktop.
Save vitoksmile/8ec271692b7c5b6c4e415ebb6914ba97 to your computer and use it in GitHub Desktop.
Mastering delays in Android
@Composable
fun LifecycleEventCoroutineEffect(
event: Lifecycle.Event,
coroutineScope: CoroutineScope = rememberCoroutineScope(),
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent: suspend CoroutineScope.() -> Unit,
) {
if (event == Lifecycle.Event.ON_DESTROY) {
throw IllegalArgumentException(
"LifecycleEventEffect cannot be used to " +
"listen for Lifecycle.Event.ON_DESTROY, since Compose disposes of the " +
"composition before ON_DESTROY observers are invoked."
)
}
var job by remember(event, coroutineScope, lifecycleOwner) { mutableStateOf<Job?>(null) }
// Safely update the current `onEvent` lambda when a new one is provided
val currentOnEvent by rememberUpdatedState(onEvent)
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, e ->
when {
e == event -> {
job = coroutineScope.launch { currentOnEvent() }
}
!lifecycleOwner.lifecycle.currentState.isAtLeast(event.targetState) -> {
job?.cancel()
job = null
}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment