This message was deleted.
# flow
s
This message was deleted.
m
d
We have these two helper methods that work for us nicely:
Copy code
/**
 * 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)
        }
    }
}
Is this a RecyclerView by any chance?