android - What is the appropriate way of calling suspending functions inside a suspendCoroutine block?
问题描述
I need to call a suspending function inside a suspendCoroutine
block, before I call continuation.resume()
.
What is the appropriate way of doing that?
private suspend fun someFunction() = suspendCoroutine { cont ->
//...
val myResult = mySuspendingFunction() //<--- The IDE says "Suspension functions can be called only within coroutine body"
cont.resume(myResult)
}
解决方案
You can't call a suspend
function in suspendCoroutine
block, because it accepts non suspend block as parameter:
suspend inline fun <T> suspendCoroutine(
crossinline block: (Continuation<T>) -> Unit
): T
'suspendCoroutine' mainly used when we have some legacy code with callbacks, e.g.:
suspend fun getUser(id: String): User = suspendCoroutine { continuation ->
Api.getUser(id) { user ->
continuation.resume(user)
}
}
If function someFunction()
doesn't call Api with callbacks then you should reconsider your approach getting rid of 'suspendCoroutine':
private suspend fun someFunction() {
// ...
val myResult = mySuspendingFunction()
// ...
}
If you still want to use suspendCoroutine
move call of mySuspendingFunction
out of suspendCoroutine
block:
private suspend fun someFunction(): String {
val myResult = mySuspendingFunction()
return suspendCoroutine { cont ->
//...
cont.resume(myResult)
}
}
suspend fun mySuspendingFunction(): String {
delay(1000) // simulate request
return "result"
}
推荐阅读
- javascript - 在 Canvas 中剪切图像
- r - R:在输出上没有 NA 的循环练习
- mysql - 如何检查mysql中的其他条件
- variables - 在ansible中使用extra-var调用定义的变量
- h2o - 在 python 中将 h2o.ai 模型保存到 S3 存储桶
- javascript - Object.assign({}, item) 将对象合并为一个不起作用
- ruby - 如何使用 Ruby 解析特定文件的 git diff?
- android - 一个活动滚动问题中的两个recycleviews
- bash - 通过命令行传递一个数组以使用 getopts() 处理
- python - 用 python / rdflib 解析海龟,不能指定 IRI 前缀