repeatOnLifecycle #71
Answered
by
arkivanov
Muhammadali143904
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
arkivanov
Sep 27, 2022
Replies: 2 comments 1 reply
-
There are codes, which i try to merge with essenty |
Beta Was this translation helpful? Give feedback.
0 replies
-
This is just from the top of my head, but I guess it should work. fun <T> Flow<T>.flowWithLifecycle(
lifecycle: Lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
): Flow<T> {
require(minActiveState !== Lifecycle.State.INITIALIZED) {
"flowWithLifecycle cannot start work with minActiveState = Lifecycle.State.INITIALIZED"
}
return callbackFlow {
val scope = CoroutineScope(Dispatchers.Main.immediate)
var job: Job? = null
fun start() {
job = scope.launch { collect { send(it) } }
}
fun stop() {
job?.cancel()
job = null
}
when (minActiveState) {
Lifecycle.State.CREATED -> lifecycle.subscribe(onCreate = ::start, onDestroy = ::stop)
Lifecycle.State.STARTED -> lifecycle.subscribe(onStart = ::start, onStop = ::stop)
Lifecycle.State.RESUMED -> lifecycle.subscribe(onResume = ::start, onPause = ::stop)
Lifecycle.State.DESTROYED,
Lifecycle.State.INITIALIZED -> Unit
}
awaitClose { scope.cancel() }
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Muhammadali143904
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is just from the top of my head, but I guess it should work.