Dmytro Danylyk
03/12/2019, 5:02 AMasync
, coroutineScope
and exception handling. When coroutineScope
is moved into separate function, I am able to catch exception inside coroutine. When coroutineScope
is declared inside coroutine, I am not able to catch exception.
This code works fine:
suspend fun doWork(): Deferred<String> = coroutineScope {
async(<http://Dispatchers.IO|Dispatchers.IO>) {
throw IllegalArgumentException()
}
}
// works fine
fun loadData() = scope.launch {
try {
doWork().await()
} catch (e: Exception) {
// exception is caught here
}
}
This doesn’t.
// crash FATAL EXCEPTION: DefaultDispatcher-worker-3 @coroutine#1
fun loadData() = scope.launch {
try {
val deferred = coroutineScope {
scope.async(<http://Dispatchers.IO|Dispatchers.IO>) {
throw IllegalArgumentException()
}
}
deferred.await()
} catch (e: Exception) {
// exception is NOT caught here
}
}
gildor
03/12/2019, 5:14 AMDmytro Danylyk
03/12/2019, 5:15 AMgildor
03/12/2019, 5:15 AMDmytro Danylyk
03/12/2019, 5:17 AMcoroutineScope
into separate method.gildor
03/12/2019, 5:17 AMsuspend fun doWork(): Deferred<String> = coroutineScope {
async(<http://Dispatchers.IO|Dispatchers.IO>) {
First, check docs of coroutineScope, this function returns only when all child coroutines are finished, I belive this is not what you expect, instead pass coroutinecontext from outsideDmytro Danylyk
03/12/2019, 5:18 AM*
* suspend fun loadDataForUI() = coroutineScope {
*
* val data = async { // <- extension on current scope
* ... load some UI data ...
* }
*
* withContext(UI) {
* doSomeWork()
* val result = data.await()
* display(result)
* }
* }
*
gildor
03/12/2019, 5:19 AMawait()