Skip to content

Instantly share code, notes, and snippets.

@fergusonm
Created January 26, 2021 23:07
Show Gist options
  • Save fergusonm/0124ed7171e36532b243051cf9eb3f2b to your computer and use it in GitHub Desktop.
Save fergusonm/0124ed7171e36532b243051cf9eb3f2b to your computer and use it in GitHub Desktop.
Flow observer
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, {})
@shalva97
Copy link

Hi, I can not import source.lifecycleScope. Which library do I need for it?

@fergusonm
Copy link
Author

fergusonm commented Apr 15, 2022

Probably one one the dependencies described in here: https://developer.android.com/topic/libraries/architecture/coroutines

@okunoyewaya
Copy link

What is this flow observer used for please?

@fergusonm
Copy link
Author

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