Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active April 14, 2022 05:08
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