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)
//...