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

Tuan Kiet

06/02/2019, 12:23 PM
I wonder what is the use case of SupervisorJob, what is the case that you don’t care about your children job might throw an exception?
t

tseisel

06/02/2019, 12:29 PM
It's not really that you don't care about children throwing an exception ; it's rather that you don't want other children to be cancelled when one fails. The first use-case that comes to my mind is "executing concurrent and independent HTTP requests".
g

gildor

06/02/2019, 12:35 PM
Just a couple examples where you actually must use supervisor job: 1. Web application, it has application scope, and launch coroutine on each requiest, you don't want cancel other coroutines (request handlers)and of course you don't want to cancel application scope, otherwise you cannot handle new requests 2. Some UI application screen, it's of course make sense to create scope per screen (it has own lifecycle), and all async operation on this screen running on the screen's scope, but some of them may fail, you don't want to cancel all other or prevent from starting new one In both of those cases you should use supervisor job for scope, in this case one failed coroutine will not cancel others, but it doesn't mean that you don't care about exceptions, unhandled exception in launch or unhandled exception on async.await() may just crash application, but also you can use coroutine exception handler on scope to catch them
t

Tuan Kiet

06/02/2019, 12:39 PM
use coroutine exception handler on scope to catch them
can I use this with regular job?
I never use SupervisorJob before, about the ui application stuff, what I do is wrapping each interactor with
runCatching
in the call side and handle exception directly from there (maybe not if I don’t want to). Not sure SupervisorJob is a good fix for this?
g

gildor

06/02/2019, 12:47 PM
Handling exceptions is fine, but imagine if you forgot to handle something, in this case it may cause scope cancellation so you cannot run anything else there, even if you handle it on on await() call side (for async)
No, exception handler will not work for regular job, you cannot prevent scope from cancellation
Again, SupervisorJob is not a way to manage your exceptions, this is coroutine lifecycle mangement strategy
And it especially important for async, where you have a way to handle exception on call site, because async encapsulate exception
t

Tuan Kiet

06/02/2019, 1:29 PM
So SupervisorJob is not for manage exception, the only valid use case for it is some kind of back off strategy? like a safe guard?
g

gildor

06/02/2019, 2:45 PM
No
SupervisorJob is exactly what I wrote above, how scope cancellation works
I also recommend to read official guide about error handling, it has section about supervision https://kotlinlang.org/docs/reference/coroutines/exception-handling.html
👍 1
4 Views