Skip to content

Instantly share code, notes, and snippets.

@fergusonm
Created October 21, 2021 21:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fergusonm/b8cb267a1319b25e11c0d73613f956c4 to your computer and use it in GitHub Desktop.
Save fergusonm/b8cb267a1319b25e11c0d73613f956c4 to your computer and use it in GitHub Desktop.
Flow with lifecycle extension functions
inline fun <reified T> Flow<T>.observeWithLifecycle(
lifecycleOwner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
noinline action: suspend (T) -> Unit
): Job = lifecycleOwner.lifecycleScope.launch {
flowWithLifecycle(lifecycleOwner.lifecycle, minActiveState).collect(action)
}
inline fun <reified T> Flow<T>.observeWithLifecycle(
fragment: Fragment,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
noinline action: suspend (T) -> Unit
): Job = fragment.viewLifecycleOwner.lifecycleScope.launch {
flowWithLifecycle(fragment.viewLifecycleOwner.lifecycle, minActiveState).collect(action)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment