-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[HELP] A way of knowing whether a flow is being collected (analogue of LiveData's onActive()/onInactive()) #2194
Comments
@psteiger per #2034 (comment):
It's not available yet, but per #2069 (comment), they:
I believe |
This is going to be available in the upcoming shared flow. See its design as explained in #2034. |
A heads-up on this issue:
What I ended up doing is, instead of relying on pausable coroutines, using coroutines that get canceled on class Observer<T>(
lifecycleOwner: LifecycleOwner,
private val flow: Flow<T>,
private val collector: suspend (T) -> Unit
) : DefaultLifecycleObserver {
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
) = Observer(lifecycleOwner, this, collector)
inline fun <reified T> Flow<T>.observeIn(
lifecycleOwner: LifecycleOwner
) = Observer(lifecycleOwner, this, {}) Then I launch such coroutine with: sharedFlow.observe(lifecycleOwner) {
// ...
} |
Hello Kotlin community,
Ever since I migrated fully from LiveData to Flow/StateFlow, I miss a way for knowing whether a
StateFlow
is being collected in order to start or stop the upstream flow collection, which can be done with LiveData'sonActive()
/onInactive()
callbacks.Example:
What I need is a way of knowing whether
peer
is being collected, so IstartUpstreamCollection()
. Also the symmetric: stop collection when there are nopeer
collectors.Could someone shed some light into this issue? Am I missing something?
The text was updated successfully, but these errors were encountered: