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

spand

11/28/2018, 8:19 AM
If I use the pattern of using a
Job()
as an explicit lifecycle as mentioned here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#cancellation-via-explicit-job Is installing a
CoroutineExceptionHandler
the only way to handle exceptions in the lifecycle ?
g

gildor

11/28/2018, 8:21 AM
exceptions in the lifecycle? What do you mean?
error handling depends on how you run your coroutines and which coroutine builder you use
s

spand

11/28/2018, 8:24 AM
In the example if it threw an exception instead of
println("Coroutine $i is done")
g

gildor

11/28/2018, 8:26 AM
launch will throw exception, this is how launch works
so or wrap code inside of launch to try catch, or use CoroutineExceptionHandler
s

spand

11/28/2018, 8:27 AM
So there is no way to extract the exception from the
job
?
I think previously I had something like
Copy code
try { job.join() } catch (e: Exception) { handleException }
g

gildor

11/28/2018, 8:29 AM
no, this is not how launch works
s

spand

11/28/2018, 8:29 AM
But I think that stopped working after structured concurrency
g

gildor

11/28/2018, 8:29 AM
Job is just to control lifecycle not to get results
No it never worked like that. there is
deferred.await()
which throws exception, not
join()
Structured concurrency changed this, it’s true, but just in terms, that you can try/catch/finally exception, but if child is crashed, parent will be also cancelled to avoid leaking of other coroutines. To use old behaviour you need SupervisorJob, in this case crash of child will not cancel parent and it’s your responsibility to manage running coroutines in case of error
👍 1
s

spand

11/28/2018, 8:30 AM
Hmm ok. Thanks
g

gildor

11/28/2018, 8:32 AM
If you need something like
try { job.join() }
use asinc/await instead of launch:
try { deferred.await() }
t

Tolriq

11/28/2018, 10:59 AM
Beware that async/await even with try catch does cancel the parent job and SupervisorJob maybe needed in some cases depending on what you want to achieve.
6 Views