Before structured concurrency, such code would run...
# coroutines
l
Before structured concurrency, such code would run properly:
Copy code
launch {
    val someWorkAsync = async {
        throw CustomException()
    }
    delay(100)
    try {
        someWorkAsync.await()
    } catch (e: CustomException) {
        println("Handled it! $e")
    }
}
If I understood correctly, now, the whole scope is cancelled, even though the exception is handled properly when calling
await()
. How can I get the previous behavior? Create a
Job
that has scope's job as parent, and use it for
async(…) { … }
?
m
I think you can use
supervisorScope { }
for that.
v
async(SupervisorJob(coroutineContext[Job]))
😞
but generally
withContext
should be used instead of single
async
. And for multiple asyncs there is
coroutineScope
could you please share actual use-case with such pattern?
e
Actually, there is a special code in the library that ensures that this particular pattern works as expected.
Ah, sorry. I forgot about delay. It will throw
CancellationException
, so you will not be able to catch exception with
await
. Thanks @[removed] for pointing that out.
l
The use case could be for when you pass the
Deferred
outside the coroutine, so you can await it somewhere else. I thought I used it for single line
requestPermission(…)
call on Android, but it turns out I use
CompletableDeferred
instead, so I think I have no use case at the moment.