android - 更新 Firestore 文档时出现 Coroutine JobCancellationException

标签 android firebase google-cloud-firestore kotlin-coroutines

调用 ViewModel 的 saveUser() 后,Firebase Firestore 文档已成功更新,但协程作业被取消,捕获 JobCancellationException,并且日志 “用户#${user.id}已保存!” 永远不会被打印。这种取消从何而来以及如何完成?

// ViewModel.kt

fun saveUser(user: User) {
    viewModelScope.launch(Dispatchers.IO) {
        Repository.saveUser(user)
        Log.d("test", "User #${user.id} saved !")
    }
}

// Repository.kt

suspend fun saveUser(user: User) {
    val documentReference = db
        .collection(USERS_COLLECTION).document(user.id)

    try {
        documentReference.set(user).await()
        Log.d("test", "Good")
    } catch (e: Exception) {
        Log.e("test", "Not good") // catches a JobCancellationException
    }
}

最佳答案

有东西正在取消作业,并且您的协程正在适当配合。

您的 ViewModel 可能正在被清除,因为您正在使用 viewModelScope 启动协程。 ViewModel 不应该被销毁,除非它的所有者(Fragment 或 Activity)被销毁。发生这种情况时,您是否正在尝试对 Activity 调用 finish() 或执行 Fragment 事务?

或者,协程上下文中的其他内容可能由于错误而取消作业。我的猜测是对 documentReference.set(user) 的调用导致了一些错误,并且 await() 可能正在取消该作业。

还要确保 Firestore、Jetpack 和 KTX 扩展的依赖项是最新的。这可能是一个已修复的错误。

关于android - 更新 Firestore 文档时出现 Coroutine JobCancellationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63884115/

相关文章:

reactjs - 在 onAuthStateChanged 监听器内分离 Firestore 监听器

firebase - 如何将 Firebase 再次连接到移动用户界面?

java - 如何在 Cloud Firestore 中正确构建本地化内容?

java - Android ImageSwitcher 图像到另一个 Activity

android - Cordova 找不到模块

javascript - Firebase 函数 : sync with Algolia doesn't work

javascript - 为什么我无法从 angular.js 工厂获取对象 firebase?

firebase - 使用 firebase-functions-test 运行离线测试时缺少 `client_secret`

android - Facebook SDK : not "opened" session state while creating WebDialog. FeedDialogBu​​ilder

android - Fragments 中的 ListView 空点异常