I am a beginner studying coroutines
.
Not exactly, but I have a little understanding of what a coroutine
is.
The suspend function
is also difficult, but with a little understanding.
I'm studying step by step, but there are parts I don't understand.
That's suspendCoroutine
. In the sample code, suspendCoroutine
and Continuation
used in the block appear, but I have no idea what these two are.
I've looked on other sites, but I can't find anywhere that explains it easily.
Can you explain what suspendCoroutine
and Continuation
are used for easily and, if possible, with an example?
suspendCoroutine
is a builder function that mainly used to convert callbacks into suspend
functions. Let's say for example you have some legacy (or not) Api, that uses callbacks. You can easily transform it into a suspend
function to call it in a coroutine. For example:
suspend fun getUser(id: String): User = suspendCoroutine { continuation ->
Api.getUser(id) { user ->
continuation.resume(user)
}
}
Here we have an Api function getUser
, which defined in Api
class for example like this:
fun getUser(id: String, callback: (User) -> Unit) {...}
suspendCoroutine
suspends coroutine in which it executed until we decide to continue by calling appropriate methods - Continuation.resume...
.
suspendCoroutine
mainly used when we have some legacy code with callbacks.
Using suspendCoroutine
to convert callbacks into suspend
functions makes the code sequential when you work with suspend
functions.
For example instead of having a callback hell like this:
Api.getUser(id) { user ->
Api.getProfile(user) { profile ->
Api.downloadImage(profile.imageId) { image ->
// ...
}
}
}
after you apply suspendCoroutine
to those callbacks and convert them into suspend
functions, the code will look like the following:
val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...