Erik
04/09/2020, 2:00 PMNonCancellable
(https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-non-cancellable.html) coroutine context? Just before my UI finishes (Android activity onDestroy
), I want to complete a certain async task and be sure that it finishes before the coroutine scope's (viewModelScope
) cancellation completes. So on the scope I call scope.launch(NonCancellable) { /* Do async task that must complete */ }
.
If that task takes long enough for the the scope to be cancelled before the task completes, then this will not cancel the task, but let it run. So the scope will not complete until this task finishes.
Did I just introduce a bug or make use of a feature?
Are there safer alternatives that guarantee task completion?
(:android: bonus question: in theory, if that task takes, say, a minute, or an hour, what would eventually happen to my process?)Dominaezzz
04/09/2020, 2:12 PMscope.launch {
withContext(NonCancellable) {
// Code that must complete once started.
}
}
To make sure the parent scope waits for cancellation.
Passing NonCancellable
directly into launch
breaks the parent-child relationship.Erik
04/09/2020, 4:10 PMJob
in launch() {}
. But since the purpose of NonCancellable
is to break the cancellation chain from parent to child, what is the problem? Why should I instead use launch { withContext(NonCancellable) {} }
?Dominaezzz
04/09/2020, 6:07 PM// Ex 1
coroutineScope {
launch(NonCancellable) {
delay(5000)
}
}
// Ex 2
coroutineScope {
launch {
withContext(NonCancellable) {
delay(5000)
}
}
}
Ex1 will return immediately and Ex2 will return after 5000ms. But the delay will still "run" in either case.Erik
04/10/2020, 6:50 AMlaunch
is fire and forget, i.e. return quicklytorresmi
04/10/2020, 9:26 AMGlobalScope
.
As to what what would happen to your process if the NonCancelable took a long time, I don't think it would make any difference. You might cause a leak until it's finished, but ultimately the if the process shuts down then it would stop running this task. Similar to if you had a long operation running in GlobalScope
Erik
04/10/2020, 9:59 AMDominaezzz
04/10/2020, 4:22 PMErik
04/10/2020, 9:48 PM