https://kotlinlang.org logo
#flow
Title
# flow
s

Slackbot

01/05/2022, 8:42 PM
This message was deleted.
m
d

dead.fish

01/06/2022, 10:15 AM
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?