Created
January 26, 2021 23:07
-
-
Save fergusonm/0124ed7171e36532b243051cf9eb3f2b to your computer and use it in GitHub Desktop.
Flow observer
This file contains hidden or 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
class FlowObserver<T> ( | |
lifecycleOwner: LifecycleOwner, | |
private val flow: Flow<T>, | |
private val collector: suspend (T) -> Unit | |
) { | |
private var job: Job? = null | |
init { | |
lifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { | |
source: LifecycleOwner, event: Lifecycle.Event -> | |
when (event) { | |
Lifecycle.Event.ON_START -> { | |
job = source.lifecycleScope.launch { | |
flow.collect { collector(it) } | |
} | |
} | |
Lifecycle.Event.ON_STOP -> { | |
job?.cancel() | |
job = null | |
} | |
else -> { } | |
} | |
}) | |
} | |
} | |
inline fun <reified T> Flow<T>.observeOnLifecycle( | |
lifecycleOwner: LifecycleOwner, | |
noinline collector: suspend (T) -> Unit | |
) = FlowObserver(lifecycleOwner, this, collector) | |
inline fun <reified T> Flow<T>.observeInLifecycle( | |
lifecycleOwner: LifecycleOwner | |
) = FlowObserver(lifecycleOwner, this, {}) |
Probably one one the dependencies described in here: https://developer.android.com/topic/libraries/architecture/coroutines
What is this flow observer used for please?
The extension function makes it pretty clear. It's used to observe a flow within the scope of a lifecycle.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I can not import
source.lifecycleScope
. Which library do I need for it?