Am I doing this correctly? I am trying to catch t...
# coroutines
a
Am I doing this correctly? I am trying to catch the exception if there is any occur when getting data from remote
Copy code
async(UI) {
    val fetchDataJob = bg {
        ColumnRepo.getFromRemote(22352581)
    }

    val data = fetchDataJob.await()
    info(data.id.toString())
    if (fetchDataJob.isCompletedExceptionally) {
        doSomeThingWithException(fetchDataJob.getCompletionException())
    }
}
g
I don’t know what is bg (Anko?) but I recommend to use suspend version of such function, that returns value directly instead Job (like run{} from core of kotlinx.coroutines), such API looks more natural and less error prone (you never forget to call .await() because you shouldn’t do that at all)
so your result code will looks something like:
Copy code
async(UI) {
   try {
     val data = fetchData(22352581)
     //or something like
     //val data = run(YourDispatcher) { ColumnRepo.getFromRemote(22352581) } 
     info(data.id.toString())
    } catch(e: Exception) { 
       doSomeThingWithException(e)
    }
}
a
bg()
is from Anko. And you are right, that
await()
make this single request more complecated
g
anko uses own dispatcher for bg calls. You can create you own or reuse CommonPool and replace bg{} with run(CommonPool) {} or to create your own shortcut https://github.com/Kotlin/anko/blob/master/anko/library/generated/coroutines/src/bg.kt#L25