Kshitij Patil
02/12/2021, 9:07 AMErik
02/12/2021, 11:54 AMKshitij Patil
02/12/2021, 1:43 PMGlobalScope
? I read about that and also found all examples of exception handling shown either in GlobalScope
or runBlocking
block. I also think the same but am looking for any other ways to handle my usecaseErik
02/12/2021, 5:19 PMKshitij Patil
02/13/2021, 4:18 AMlifecycleScope
of Fragment
. Idk if it has an exception handler but as you said, I've to create a scope and put exception Handler there, is exactly what I've done.
FYI, I also tried to pass exceptionHandler to launch
& async
but nothing workedErik
02/14/2021, 1:30 PMval handler = CoroutineExceptionHandler {
context, exception -> println("Caught $exception")
}
val scope = CoroutineScope(Job())
scope.launch(handler) {
launch {
throw Exception("Failed coroutine")
}
}
In the above code the exception will be handled by handler
.
However, the following code will not handle your exception in handler
, because the handler is not installed in the outer coroutine:
val scope = CoroutineScope(Job())
scope.launch {
launch(handler) {
throw Exception("Failed coroutine")
}
}
Quote from the article:
The inner launch will propagate the exception up to the parent as soon as it happens, since the parent doesn’t know anything about the handler, the exception will be thrown.
lifecycleScope.launch(handler) { /* Do exceptional stuff */ }
, or just create your own CoroutineScope(handler)
, but don't forget to cancel the scope on fragment destroy/stop/pause (depending on when you create the scope and when stuff needs to cancel)Kshitij Patil
02/14/2021, 3:07 PMscope.launch(handler) { ... }
But this doesn't work. I'll share a playground link with the code that doesn't workGlobalScope
whereas Fragment have lifecycleScope
and I'm trying to create custom scope out of it which I believe won't be able to handle exceptions. I'll give a shot to lifecycleScope.launch(handler) { }
as that seems promising but my purpose was to have a supervisorScope
, i.e. failing any child coroutine should not cause others to fail and neither cause any Runtime Exception. I'm launching independent network calls which might fail and I've a code associated with it to reflect those errors on UI, the problem is, handling exceptions seperately for each job gives me the desired effect but I lose the ability to get to know whether all the jobs are successful so that I can show Success Toast/Snackbar at the very endErik
02/16/2021, 7:02 AMasync {}
for that: do many calls in parallel and then await()
all `Deferred<T>`: awaiting rethrows exceptions that happened in the block which you can simply try
-catch
. If anything you expect is caught, you can show your UI notice.Kshitij Patil
02/16/2021, 10:23 AMexceptionHandler