Created
March 3, 2025 16:10
-
-
Save vitoksmile/8ec271692b7c5b6c4e415ebb6914ba97 to your computer and use it in GitHub Desktop.
Mastering delays in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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