Skip to content

Instantly share code, notes, and snippets.

@boswelja
Last active April 15, 2022 08:38
Show Gist options
  • Save boswelja/ae9fd1855e8074c92421fa000f7bf3c9 to your computer and use it in GitHub Desktop.
Save boswelja/ae9fd1855e8074c92421fa000f7bf3c9 to your computer and use it in GitHub Desktop.
Single-line Flow collector tied to Android's lifecycle
/**
* Observe a Flow on the calling lifecycle. This functions similar to LiveData observe, where
* collectors are tied to the calling scope's lifecycle. Using this, we can avoid having to launch
* a coroutine scope + using repeatOnLifecycle every time.
* @param lifecycleState The lifecycle state to start collecting the Flow on. Collection will be
* cancelled in the mirror state. See [repeatOnLifecycle] for more details.
* @param collector The [FlowCollector] used to collect values. See [Flow.collect] for more details.
*/
context(LifecycleOwner)
fun <T> Flow<T>.observe(
lifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
collector: FlowCollector<T>
) {
lifecycleScope.launch {
repeatOnLifecycle(lifecycleState) {
collect(collector)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment