https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

louiscad

10/24/2018, 2:22 PM
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

marstran

10/24/2018, 2:24 PM
I think you can use
supervisorScope { }
for that.
v

Vsevolod Tolstopyatov [JB]

10/24/2018, 2:26 PM
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

elizarov

10/24/2018, 2:53 PM
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

louiscad

10/24/2018, 10:56 PM
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.