-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Exception thrown by async is not caught when parent job is cancelled. #875
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The stacktrace is like this
This issue starts to raise right after we upgrade kotlin to 1.3.0. I'm wondering if there's any behavior change that i'm not aware of? |
From the docs on GlobalScope :
You shouldn't use |
Using |
@qwwdfsad Yeah, you're right in this particular case. But what if we do need |
Then recommended solution is to wrap them into E.g.
|
So is there any semantic difference between using |
When destroying your Activity, you should cancel it's scope, which means the children you launched will be cancelled as well (as to not leave orphaned background tasks running) |
Yeah I understand. Actually I don't think binding a scope to activity can relieve developers of the complexity of asynchronous programming. In our practice we find that cancel parent job when destroying activity helps very little. We still need to check UI state after an async job, due to the fact that cancellation of coroutine is cooperative. And async job throwing exception on thread pool instead of being caught makes it even harder to use correctly. |
@yihuaqi I have an exact same issue how do u solve that problem ? |
We use add an CoroutineExceptionHandler for every coroutine we start to avoid crash for now. |
Sample code for the scenario.
We have a contextJob in activity as the parent job of all coroutines which is cancelled in onDestroy(), as recommended in official guide.
The problem is that when the contextJob is cancelled while the async job is executing, the exception thrown by async will not be caught by the try...catch... block , and thus crashes our app.
I'm aware that CoroutineExceptionHandler can catch the exception, but then it brings a huge mental load during development. I would rather to not use contextJob at all.
When is the recommended way of dealing with this situation?
The text was updated successfully, but these errors were encountered: