Manas Marthi
07/11/2024, 6:58 AMvar resultMap = mutableMap
withContext(Dispatchers.IO) {
val job = async {
try {
//some jdbc call
result['data'] = //jdbc result
} catch (ex: Exception){
result['error'] = ex
}
}
job.await()
}
bock that fails:
var resultMap = mutableMap
val job = async(Dispatchers.IO) {
try {
//some jdbc call
result['data'] = //jdbc result
} catch (ex: Exception){
result['error'] = ex
}
}
job.await()
Sam
07/11/2024, 7:11 AMawait
immediately after starting a new coroutine is an unusual thing to do and suggests you might not need the async
block at all.Manas Marthi
07/11/2024, 7:18 AMSam
07/11/2024, 7:21 AMwithContext
function creates a coroutine scope, which allows you to launch new coroutines via async
and launch
. However, in this case, you don't need an additional coroutine, because you only have one task to perform. You can run your code directly inside the withContext
block, without async
. Starting additional coroutines here would only be necessary if you want to multitask, e.g. making two simultaneous network calls.Manas Marthi
07/11/2024, 8:42 AMwithContext
alone take care of doing non blocked IO for the jdbc call? How do I know if the thread is blocked or not?Sam
07/11/2024, 9:31 AMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
will take care of moving the blocking IO onto the IO dispatcher so it doesn't block the calling thread. It's a suspending function, so it doesn't block its caller.Manas Marthi
07/11/2024, 9:51 AMSam
07/11/2024, 9:57 AMManas Marthi
07/11/2024, 11:47 AM