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)
}

推荐答案

不能在suspendCoroutine块中调用suspend函数,因为它接受非挂起块作为参数:

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

如果您仍要使用suspendCoroutine移动呼叫,请使用suspendCoroutine块中的mySuspendingFunction:

private suspend fun someFunction(): String {
    val myResult = mySuspendingFunction()

    return suspendCoroutine { cont ->
        //...
        cont.resume(myResult)
    }
}

suspend fun mySuspendingFunction(): String {
    delay(1000) // simulate request
    return "result"
}

Kotlin相关问答推荐

Kotlin—列出具有不同T的列表之间的操作'

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

在 detekt 配置文件中找不到某些属性

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

在 kotlin 中使具体化字段可选

使用 Jetpack Compose 使用参数导航

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

比较 Kotlin 中的可比对象列表

是否可以在 kotlin 中嵌套数据类?

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

带有迭代器函数的 Kotlin 无限序列

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

kotlin-bom 库是做什么的?

Kotlin中的下划线名称是为什么保留的?

用Gradle Kotlin DSL构建源jar?

如何让数据类在Kotlin中实现接口/扩展超类属性?

如何在Kotlin中使方法param可变?

将字符串转换为HashMap的最简单方法

在Kotlin中创建通用二维数组