Last active
April 15, 2022 08:38
-
-
Save boswelja/ae9fd1855e8074c92421fa000f7bf3c9 to your computer and use it in GitHub Desktop.
Single-line Flow collector tied to Android's lifecycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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