首页 > 解决方案 > Kotlin kotlin 多挂起可取消协程

问题描述

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

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

标签: kotlincoroutine

解决方案


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

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

许多 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 没有可用的挂起功能,那么要编写您自己的 with suspendCoroutine,我建议编写一个可以与任何任务一起使用的基本版本,然后在您的特定应用程序代码中使用它。它看起来像这样:

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

推荐阅读