svenjacobs
04/05/2019, 10:09 AMJob. When I add a Job instance to a CoroutineContext the behaviour of async changes in regards to exception handling. Suddenly exceptions within async are propagated to the default exception handler. On Android for example this causes the app to crash. try .. catch around await() don't help here. It seems that Job adds the default exception handler to the context. However I need Job so that I can cancel the context later. Here's an example (yes, it's Android but it's a generic problem, not related to Android)
class TestActivity : Activity(),
CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Default + Job()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val deferred = async {
// App crashes here
throw NullPointerException()
}
launch {
try {
deferred.await()
} catch (e: Exception) {
Log.e("TestActivity", "ERROR", e)
}
}
}
override fun onDestroy() {
coroutineContext.cancel()
super.onDestroy()
}
}
How can I have the default behaviour of async where exceptions are only thrown on await() but also have the ability of a cancellable job in a context?svenjacobs
04/05/2019, 10:23 AMSupervisorJob?svenjacobs
04/05/2019, 10:48 AMSupervisorJob apparently is the correct way https://proandroiddev.com/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e#69e0louiscad
04/05/2019, 10:58 AMsvenjacobs
04/05/2019, 11:04 AMActivity implement CoroutineScope is a common pattern in Android development with coroutines. All coroutines launched in this scope are cancelled when the Activity is destroyed (as demonstrated above). I understand the use case in the slide but in this case I only have one async anyway. I understand that if I have a dependency between multiple async, I should wrap them in coroutineScope. However the outer Activity scope should stay imho.gildor
04/05/2019, 11:07 AMIt seems thatYes, it works as designed, your scope is cancelled and throw exceptionadds the default exception handler to the contextJob
gildor
04/05/2019, 11:08 AMgildor
04/05/2019, 11:09 AMsvenjacobs
04/05/2019, 11:11 AMJob to a CoroutineContext changes the exception handlingsvenjacobs
04/05/2019, 11:14 AMSupervisorJob was introduced and the problem only evident nowlouiscad
04/05/2019, 11:20 AMActivity, so Andrey's advice is the right one.gildor
04/05/2019, 12:19 PM