Kotlin 多重暂停可取消协程

标签 kotlin coroutine

我在协程方面遇到问题。我使用一个协程,我想在第一个协程中执行第二个协程。当我尝试运行第二个协程时遇到一个错误:“只能在协程体内调用暂停函数”。我到处都有协程,那么问题出在哪里呢?这是代码:

 suspend fun firstCoroutine(): List<Decks> {

    val activeLanguage = userService.getActiveLanguage() ?: return emptyList()

    return suspendCancellableCoroutine { continuation ->

        db.collection("Decks")
            .whereArrayContains("languages", activeLanguage)
            .get()
            .addOnSuccessListener { documents ->

                val items = ArrayList<Decks>()

                if (documents != null) {
                    for (document in documents) {
                        val id: String = document.id

                        var knowCountForDeck: Int = secondCoroutine(id). <-- here is problem
                        
                        val name: String = document.data["name"] as String
                        val languages: List<String> =
                            document.data["languages"] as List<String>
                        items.add(Decks(id, name, languages))
                    }

                }
                continuation.resume(items)
            }
            .addOnFailureListener { err ->
                continuation.resumeWithException(err)
            }
    }
}

suspend fun secondCoroutine(collectionId: String): Int {

    val userId = userService.getCurrentUserId() ?: return 0

    return suspendCancellableCoroutine { continuation ->

        db.collection("Users").document(userId).collection(collectionId).get()
            .addOnSuccessListener { cards ->

                var knowCountForDeck = 0

                if (!cards.isEmpty) {
                    for (card in cards) {
                        if (card.data["status"] == "know") {
                            knowCountForDeck += 1
                        }
                    }
                }
                continuation.resume(knowCountForDeck)
            }
            .addOnFailureListener { err ->
                continuation.resumeWithException(err)
            }
    }
}

最佳答案

您正在尝试从回调中调用协程,该回调不是您的协程的一部分,因此它无法调用挂起函数。

协程的主要优点之一是您可以避免使用回调并按顺序编写代码。

许多 API 已经包含使用回调的替代挂起函数。如果我对您使用的是 Firebase 的猜测是正确的,您可以使用挂起函数 await() 而不是使用监听器。那么您不需要使用 suspendCoroutinesuspendCancellableCoroutine 将回调转换为挂起函数:

suspend fun firstCoroutine(): List<Decks> {

    val activeLanguage = userService.getActiveLanguage() ?: return emptyList()

    val documents = db.collection("Decks")
        .whereArrayContains("languages", activeLanguage)
        .get()
        .await()
    val items = documents.map { document ->
        val id: String = document.id

        var knowCountForDeck: Int = someSuspendFunction(id)

        val name: String = document.data["name"] as String
        val languages: List<String> =
            document.data["languages"] as List<String>
        Decks(id, name, languages)
    }
    return items
}

如果您使用的 API 没有可用的挂起函数,那么要使用 suspendCoroutine 编写自己的 API,我建议编写一个可以与任何任务一起使用的基本版本,并且然后在您的特定应用程序代码中使用它。它看起来像这样:

suspend fun <T> Task<T>.await() = suspendCoroutine<T> { continuation ->
    addOnSuccessListener {
        continuation.resume(it)
    }
    addOnFailureListener {
        continuation.resumeWithException(it)
    }
}

或者为了更好地遵循 Kotlin 约定,您可以返回 null,而不是在可恢复的故障上抛出异常:

suspend fun <T: Any> Task<T>.awaitResultOrNull(): T? = suspendCoroutine<T> { continuation ->
    addOnSuccessListener {
        continuation.resume(it)
    }
    addOnFailureListener {
        continuation.resume(null)
    }
}

关于Kotlin 多重暂停可取消协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68529997/

相关文章:

Python 3 asyncio - yield from vs asyncio.async 堆栈使用

kotlin - 如何在 Kotlin 中使用 JpaRepository 中的 save()

javascript - 无法从 Kotlinjs 中的所需模块创建对象

android - Kotlin 懒惰使用

android - GlobalScope 与 CoroutineScope 与生命周期范围

c - 使用 setjmp() 和 longjmp() 创建斐波那契生成器序列时出错

python - 这怎么是协程?

java - 不使用rxjava如何去抖

android - 设置数据绑定(bind)时出现 Kotlin 错误

coroutine - 协程vs纤维差异澄清