kotlin - 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)
}
}
}
解决方案
您正在尝试从回调中调用协程,这不是您的协程的一部分,因此它不能调用挂起函数。
协程的主要优点之一是您可以避免使用回调并按顺序编写代码。
许多 API 已经包含使用回调的挂起函数替代方案。如果我猜测您使用的是 Firebase 是正确的,您可以使用挂起功能await()
而不是使用侦听器。然后你不需要使用suspendCoroutine
或suspendCancellableCoroutine
将你的回调转换为挂起函数:
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)
}
}
推荐阅读
- c++ - 为什么将内存分配给 char 指针不会截断 char 序列
- angular - 使用 observables (map?) 在 threejs 中加载 fbx
- json - 使用 jq 获取选定对象的父键
- laravel - Laravel 计数原始查询总是返回零
- variables - 如何在 Ansible 中取消注释多行?
- c# - 执行可通过 Windows 窗体按钮取消的后台进程
- python-3.x - 如何在 python3 中绘制 3d 轴
- swift - 在 iOS 13.2 的情况下,.normal 阶段的 UIBarButtonItem 的 TintColor 不会改变
- php - 如何更改 onclick 功能按钮中的值
- kubernetes - 如何判断我的 pod 是针对哪个 PSP 进行验证的