Does anyone know of some good articles where a sus...
# coroutines
k
Does anyone know of some good articles where a suspending function is written that deals with something like IO? I want to learn about composing a suspending function from resources which aren't suspending
m
TLDR; wrap your blocking code within
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
if the blocking API call deals with IO.
Example:
Copy code
suspend fun getUser(userId: String) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    dataStore.getUser(userId) // Blocking database query
}
k
@Marcelo Hernandez I just used IO as an example. I'm trying to get to the low level nitty gritty of coroutine's.
For example, if I wanted to call an external process and wait for that process to finish and join, how would I wrap that call and make it a suspending function?
Or reading data from a socket
m
Otherwise, if it truly is blocking, then
withContext
is what you'll have to wrap the blocking call with in order to run it within a
suspend
function.
k
suspendCoroutine
is what I'm looking for :) thanks
👍 1
m
If the blocking call is cancellable in any way, then it is recommended to use
suspendCancellableCoroutine
.
k
Yup sounds like a plan
Thanks
m
You're welcome!