Skip to content

Instantly share code, notes, and snippets.

@k0siara
Created July 14, 2021 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0siara/429929bcfc58056ad8d33e0ac0d5021d to your computer and use it in GitHub Desktop.
Save k0siara/429929bcfc58056ad8d33e0ac0d5021d to your computer and use it in GitHub Desktop.
FlowObserver
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 -> {
}
}
}
)
}
}
@InternalCoroutinesApi
inline fun <reified T> Flow<T>.observeOnLifecycle(
lifecycleOwner: LifecycleOwner,
noinline collector: suspend (T) -> Unit
) = FlowObserver(lifecycleOwner, this, collector)
@InternalCoroutinesApi
fun <T> Flow<T>.observeInLifecycle(
lifecycleOwner: LifecycleOwner
) = FlowObserver(lifecycleOwner, this, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment