Created
July 14, 2021 19:32
-
-
Save k0siara/429929bcfc58056ad8d33e0ac0d5021d to your computer and use it in GitHub Desktop.
FlowObserver
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 -> { | |
} | |
} | |
} | |
) | |
} | |
} | |
@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