Slackbot
01/05/2022, 8:42 PMms
01/06/2022, 5:54 AMrepeatOnLifecycle
API
https://medium.com/androiddevelopers/repeatonlifecycle-api-design-story-8670d1a7d333dead.fish
01/06/2022, 10:15 AM/**
* Subscribes to a flow every time the Activity transits into the STARTED state.
* Terminates the coroutine as soon as the lifecycle reaches the STOPPED state.
*/
fun <T> Flow<T>.collectWhileVisible(activity: ComponentActivity, collector: suspend (T) -> Unit) =
collectWhileVisible(activity as LifecycleOwner, collector)
/**
* Subscribes to a flow every time the Fragment's View transits into the STARTED state.
* Terminates the coroutine as soon as the lifecycle reaches the STOPPED state.
*/
fun <T> Flow<T>.collectWhileVisible(fragment: Fragment, collector: suspend (T) -> Unit) =
collectWhileVisible(fragment.viewLifecycleOwner, collector)
private fun <T> Flow<T>.collectWhileVisible(lifecycleOwner: LifecycleOwner, collector: suspend (T) -> Unit) {
lifecycleOwner.lifecycleScope.launch {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
collect(collector)
}
}
}
dead.fish
01/06/2022, 5:24 PM