https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kevin.cianfarini

03/11/2019, 3:00 PM
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

Marcelo Hernandez

03/11/2019, 4:48 PM
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

kevin.cianfarini

03/12/2019, 12:09 AM
@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

Marcelo Hernandez

03/12/2019, 12:12 AM
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

kevin.cianfarini

03/12/2019, 12:18 AM
suspendCoroutine
is what I'm looking for :) thanks
👍 1
m

Marcelo Hernandez

03/12/2019, 12:19 AM
If the blocking call is cancellable in any way, then it is recommended to use
suspendCancellableCoroutine
.
k

kevin.cianfarini

03/12/2019, 12:19 AM
Yup sounds like a plan
Thanks
m

Marcelo Hernandez

03/12/2019, 12:20 AM
You're welcome!
2 Views