Skip to content

Instantly share code, notes, and snippets.

@mcatta
Created December 20, 2023 16:28
Show Gist options
  • Save mcatta/f74d68bb44c1e71578e43c95c776a0dc to your computer and use it in GitHub Desktop.
Save mcatta/f74d68bb44c1e71578e43c95c776a0dc to your computer and use it in GitHub Desktop.
A composable function that allows you to handle side-effect just once
/**
* Composable function that aims to help the single event handing.
* Use it only for SideEffect event (one shot) and not for handling UI state changes.
*
* @param sideEffectFlow Flow
* @param lifeCycleState default [Lifecycle.State.STARTED]
* @param collector
*/
@Composable
fun <T : Any> SingleEventEffect(
sideEffectFlow: Flow<T>,
lifeCycleState: Lifecycle.State = Lifecycle.State.STARTED,
collector: (T) -> Unit
) {
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(sideEffectFlow) {
lifecycleOwner.repeatOnLifecycle(lifeCycleState) {
sideEffectFlow.collect(collector)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment