我将我的一个应用程序转换为新的 Firestore。我正在做一些事情,比如单击按钮保存文档,然后在 onSuccess
监听器中,转到不同的 Activity 。
我还利用 Firestore 保存操作返回任务这一事实,使用 Tasks.whenAll
将任务组合在一起:
val allTasks = Tasks.whenAll(
createSupporter(supporter),,
setStreetLookup(makeStreetKey(supporter.street_name)),
updateCircleChartForUser(statusChange, createMode = true),
updateStatusCountForUser(statusChange))
allTasks.addOnSuccessListener(this@SignUpActivity, successListener)
allTasks.addOnFailureListener(this@SignUpActivity, onFailureListener)
最后,我从成功保存中获取文档 ID,并将其存储在首选项或本地数据库中以备后用(在 onSuccessListener
中)
这一切都很好。 直到网络连接中断。然后一切都崩溃了,因为任务永远不会完成并且永远不会调用 onSuccess/onFailure/onComplete 监听器。所以应用程序只是挂起。
我正在通过在每次保存之前检查网络可用性来解决这个问题,然后通过创建没有任何监听器的任务来解决这个问题。我还使用 UUID 生成器在本地生成文档 ID。
顺便说一句,这不是应用程序与旧 Firebase 一起工作的方式。在那种情况下,离线时一切都运行良好,我看到只要应用程序上线,文档就会同步。
我的 Firestore 解决方法似乎很糟糕。有没有人提出更好的解决方案?
查看相关Firestore database on insert/delete document callbacks not being invoked when there is no connection addOnCompleteListener not called offline with cloud firestore
最佳答案
Cloud Firestore 为我们提供了处理离线数据的功能,但您需要使用“快照”(QuerySnapshot、DocumentSnapshot)来处理这种情况,不幸的是它没有很好的记录。这是一些使用快照处理案例的代码示例(我使用 Kotlin Android):
更新数据:
db.collection("members").document(id)
.addSnapshotListener(object : EventListener<DocumentSnapshot> {
override fun onEvent(snapshot: DocumentSnapshot?,
e: FirebaseFirestoreException?) {
if (e != null) {
Log.w(ContentValues.TAG, "Listen error", e)
err_msg.text = e.message
err_msg.visibility = View.VISIBLE;
return
}
snapshot?.reference?.update(data)
}
})
添加数据:
db.collection("members").document()
.addSnapshotListener(object : EventListener<DocumentSnapshot> {
override fun onEvent(snapshot: DocumentSnapshot?,
e: FirebaseFirestoreException?) {
if (e != null) {
Log.w(ContentValues.TAG, "Listen error", e)
err_msg.text = e.message
err_msg.visibility = View.VISIBLE;
return
}
snapshot?.reference?.set(data)
}
})
删除数据:
db.collection("members").document(list_member[position].id)
.addSnapshotListener(object : EventListener<DocumentSnapshot> {
override fun onEvent(snapshot: DocumentSnapshot?,
e: FirebaseFirestoreException?) {
if (e != null) {
Log.w(ContentValues.TAG, "Listen error", e)
return
}
snapshot?.reference?.delete()
}
})
您可以在此处查看代码示例:https://github.com/sabithuraira/KotlinFirestore和博客文章 http://blog.farifam.com/2017/11/28/android-kotlin-management-offline-firestore-data-automatically-sync-it/
关于android - Firestore 与 Firebase 的离线问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843218/