Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active April 14, 2022 05:08
Show Gist options
  • Save benigumocom/16e381c3dcd00e37254832f5300e2c61 to your computer and use it in GitHub Desktop.
Save benigumocom/16e381c3dcd00e37254832f5300e2c61 to your computer and use it in GitHub Desktop.
RepeatOnLifecycle in Fragment
/**
* Launches a new coroutine and repeats `block` every time the Fragment's viewLifecycleOwner
* is in and out of `minActiveState` lifecycle state.
*/
inline fun Fragment.launchAndRepeatWithViewLifecycle(
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
crossinline block: suspend CoroutineScope.() -> Unit
) {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
block()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment