suspendCoroutine
是一个构建器函数,主要用于将回调转换为suspend
功能。举例来说,假设您有一些使用回调的遗留(或没有)Api。您可以轻松地将其转换为suspend
函数在协程中调用它。例如:
suspend fun getUser(id: String): User = suspendCoroutine { continuation ->
Api.getUser(id) { user ->
continuation.resume(user)
}
}
这里我们有一个Api函数getUser
,其定义在Api
类例如这样:
fun getUser(id: String, callback: (User) -> Unit) {...}
suspendCoroutine
暂停执行它的协程,直到我们决定通过调用适当的方法继续 -Continuation.resume...
.
suspendCoroutine
主要在我们有一些带有回调的遗留代码时使用。
Using suspendCoroutine
将回调转换为suspend
当您使用函数时,函数使代码顺序化suspend
功能。
例如,不要像这样有一个回调地狱:
Api.getUser(id) { user ->
Api.getProfile(user) { profile ->
Api.downloadImage(profile.imageId) { image ->
// ...
}
}
}
申请后suspendCoroutine
到这些回调并将它们转换为suspend
函数,代码如下所示:
val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...