ursus
09/18/2024, 6:41 PMclass MyWorker {
private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
suspend fun doStuff() {
val deferred = scope.async {
...some async stuff
}
deferred.await()
}
}
This tries to not be cancelled by running the operation on it's own scope - yet it awaits the deferred
Does this code break structured concurrency?Sam
09/18/2024, 6:45 PMursus
09/18/2024, 6:46 PMursus
09/18/2024, 6:48 PMdoStuff
finish (not get cancelled), even if the calling scope is gone (viewmodel)Sam
09/18/2024, 6:49 PMwithContext(NonCancellable)
ursus
09/18/2024, 6:49 PMursus
09/18/2024, 6:51 PMdoStuff
to get cancelled when it's parent dies, like user ,ie. logout
so it should not blankly finish no matter what
it just should not be scoped to the view model, from which it is launchedursus
09/18/2024, 6:51 PMclass MyWorker {
private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
fun doStuff() {
scope.launch {
...some async stuff
}
}
}
does this still break structured concurrency?Sam
09/18/2024, 6:56 PMscope
, I think either approach you showed is fine. It sounds like that's the case, since you said that doStuff
should still be cancelled if its parent dies. It's okay for coroutines in one scope to launch and await coroutines in another, provided you take care with cancellation exceptions.Sam
09/18/2024, 6:58 PMursus
09/18/2024, 6:58 PMIt's okay for coroutines in one scope to launch and await coroutines in anotherbut doesn't this exactly break structured concurrency? i.e. the caller's scope doesnt control it's launched coroutines
ursus
09/18/2024, 6:59 PMCreating a new scope without any cancellation just so you can launch coroutines without waiting for them = breaking structured concurrency.how so? just because the
private val scope
is not explicitly cancelled? (I ommited that for brevity)Sam
09/18/2024, 7:00 PMursus
09/18/2024, 7:01 PMursus
09/18/2024, 7:02 PMclass MyWorker {
private val scope = CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>)
fun doStuff() {
scope.launch {
...some async stuff
}
}
}
should not break structured concurrency, as it does not apply .. it's a blocking function, doesnt participate ..no?Sam
09/18/2024, 7:08 PMursus
09/18/2024, 7:08 PMursus
09/18/2024, 7:09 PMSam
09/18/2024, 7:12 PMursus
09/18/2024, 7:15 PMursus
09/18/2024, 7:15 PMSam
09/18/2024, 7:17 PMursus
09/18/2024, 7:17 PMSam
09/18/2024, 7:21 PMursus
09/18/2024, 7:21 PMSam
09/18/2024, 7:26 PMSam
09/18/2024, 7:26 PMursus
09/18/2024, 7:27 PMSam
09/18/2024, 7:30 PMursus
09/18/2024, 7:30 PMursus
09/18/2024, 7:31 PM