Skip to content

Instantly share code, notes, and snippets.

@krzdabrowski
Last active August 10, 2022 16:20
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 krzdabrowski/d5c40d162871ed8d01f8dac97b2da007 to your computer and use it in GitHub Desktop.
Save krzdabrowski/d5c40d162871ed8d01f8dac97b2da007 to your computer and use it in GitHub Desktop.
@Composable
inline fun <reified T> Flow<T>.collectWithLifecycle(
key: Any = Unit,
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
noinline action: suspend (T) -> Unit
) {
val lifecycleAwareFlow = remember(this, lifecycleOwner) {
flowWithLifecycle(
lifecycle = lifecycleOwner.lifecycle,
minActiveState = minActiveState
)
}
LaunchedEffect(key) {
lifecycleAwareFlow.collect { action(it) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment