Last active
November 23, 2020 17:04
-
-
Save psteiger/10e2ade41a078166250d35ae93dfc699 to your computer and use it in GitHub Desktop.
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
@PublishedApi | |
internal class ObserverImpl<T> ( | |
lifecycleOwner: LifecycleOwner, | |
private val flow: Flow<T>, | |
private val collector: suspend (T) -> Unit | |
) : DefaultLifecycleObserver { | |
private var job: Job? = null | |
override fun onStart(owner: LifecycleOwner) { | |
job = owner.lifecycleScope.launch { | |
flow.collect { | |
collector(it) | |
} | |
} | |
} | |
override fun onStop(owner: LifecycleOwner) { | |
job?.cancel() | |
job = null | |
} | |
init { | |
lifecycleOwner.lifecycle.addObserver(this) | |
} | |
} | |
inline fun <reified T> Flow<T>.observe( | |
lifecycleOwner: LifecycleOwner, | |
noinline collector: suspend (T) -> Unit | |
) { | |
ObserverImpl(lifecycleOwner, this, collector) | |
} | |
inline fun <reified T> Flow<T>.observeIn( | |
lifecycleOwner: LifecycleOwner | |
) { | |
ObserverImpl(lifecycleOwner, this, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment