Hong Phuc
12/15/2024, 4:28 AMcoroutine
is correct. When a coroutine hit a suspension point (like an await()
call), it is paused from the thread that it was called from (depend on the Dispatcher
), so that the thread can continue execute other codes and then the excution of the function that calls await()
in the coroutine
if offloaded to another thread in the `Dispatcher`'s thread pool? Thanks in advanceSam
12/15/2024, 7:41 AMawait()
suspends its coroutine, it's no longer executing any code, so the second part of your message isn't quite right. The call to await()
doesn't need to offload anything to other threads in its dispatcher's thread pool. Instead, the task/event that it's waiting for is responsible for its own execution, and will notify the suspended coroutine when it's time to resume.Hong Phuc
12/15/2024, 10:32 AMconnection
do a executeQuery
call inside a suspension function, how does the couroutine know where is the suspension point so it can vacate the thread?Sam
12/15/2024, 10:48 AMStatement.executeQuery()
, that function doesn't contain any suspension points, and so the coroutine would never be able to vacate the thread. There are two options to fix that:
1. Use a different function. It could be one that's written with suspension points from the ground up, or it could be written with asynchronous callbacks/futures that are converted into a suspension point.
2. Use withContext(<http://Dispatchers.IO|Dispatchers.IO>) {…}
to offload the query to a designated I/O thread. This lets the caller suspend (i.e. vacate its thread) while it waits for the code inside the withContext
block to be executed. Maybe this is similar to what you were imagining in your original question.Sam
12/15/2024, 10:59 AMsuspendCoroutine
or suspendCancellableCoroutine
, which is the explicit instruction that tells the coroutine to enter that paused state you were describing.Hong Phuc
12/15/2024, 8:30 PMsuspendCoroutine
🙂