tad
07/29/2021, 7:42 PMlifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
try {
session.load()
awaitCancellation()
} finally {
runBlocking {
// This is a suspending function that performs I/O and needs to complete.
session.recordBackgroundTime()
}
}
}
}
uli
07/29/2021, 7:49 PMtad
07/29/2021, 7:51 PMlifecycleScope
is canceled and the I/O coroutine inside session.recordBackgroundTime
does not run.uli
07/29/2021, 7:53 PMtad
07/29/2021, 7:54 PMlateinit var
or nullable property by using awaitCancellation()
in the lifecycle scopeNick Allen
07/29/2021, 7:55 PMuli
07/29/2021, 7:55 PMtad
07/29/2021, 7:56 PMuli
07/29/2021, 7:56 PMtad
07/29/2021, 7:57 PMrepeatOnLifecycle
block is cancelled when the lifecycle exits the STARTED state (it is stopped)uli
07/29/2021, 8:01 PMtad
07/29/2021, 8:03 PMwithContext(NonCancellable)
is working and feels like the correct thing to do here.Nick Allen
07/29/2021, 8:05 PMephemient
07/29/2021, 8:08 PMuli
07/29/2021, 8:09 PMtad
07/29/2021, 8:09 PMNonCancellable
, unless I'm not understanding what happens here.ephemient
07/29/2021, 8:12 PMwithContext(Main)
GlobalScope.launch {}
might be a reasonable, but should also be used with cautiontad
07/29/2021, 8:15 PMNonCancellable
(and presumably with GlobalScope) the handler ends up running after re-starting the activityephemient
07/29/2021, 8:16 PMuli
07/29/2021, 8:18 PMtad
07/29/2021, 8:19 PMuli
07/29/2021, 8:20 PMtad
07/29/2021, 8:20 PMephemient
07/29/2021, 8:20 PMuli
07/29/2021, 8:21 PMtad
07/29/2021, 8:21 PMuli
07/29/2021, 8:21 PMNick Allen
07/29/2021, 8:23 PMephemient
07/29/2021, 8:23 PMuli
07/29/2021, 8:24 PMtad
07/29/2021, 8:24 PMrecordBackgroundTime
Nick Allen
07/29/2021, 8:24 PMtad
07/29/2021, 8:25 PMuli
07/29/2021, 8:27 PMephemient
07/29/2021, 8:27 PMuli
07/29/2021, 8:31 PMgildor
07/30/2021, 2:41 AM> // This is a suspending function that performs I/O and needs to complete.
If your function is suspend, there is no reason to warp it to runBlocking, you block your main thread, just remove runBlocking and it will worktad
07/30/2021, 7:55 PMawaitCancellation()
, the function is called, suspended (as it uses withContext(<http://Dispatchers.IO|Dispatchers.IO>)
internally), and the parent scope is cancelled before the function performs the save.gildor
08/01/2021, 3:53 AM