【问题标题】:How to get a DocumentChange object for a single document from Firestore collection in Kotlin?如何从 Kotlin 的 Firestore 集合中获取单个文档的 DocumentChange 对象?
【发布时间】:2020-06-01 11:08:05
【问题描述】:

如何获取单个 documentSnapshot 的 DocumentChange 对象? 我想在我的 when 语句中使用文档更改的类型。使用 querySnapshot 很容易,但我不知道如何解决这个问题以收听单个文档的更改。

val uid = FirebaseAuth.getInstance().uid
val documentReference = FirebaseFirestore.getInstance().collection("users").document(uid!!)
        documentReference.addSnapshotListener{
            documentSnapshot, e ->
            when (documentSnapshot**what code needs to be here**.type) {
                DocumentChange.Type.ADDED -> {}
                DocumentChange.Type.MODIFIED -> {}
                DocumentChange.Type.REMOVED -> {}
            }
        }

【问题讨论】:

    标签: kotlin google-cloud-firestore listener


    【解决方案1】:

    收听单个文档时不会收到DocumentChange.Type。相反,您会得到一个包含该文档状态的 DocumentSnapshot

    您可以通过查看文档得出发生了什么,并跟踪这是否是您的侦听器的第一个回调:

    if (snapshot.exists()) {
      if (isFirst) Log.i(TAG, "ADDED")
      else Log.i(TAG, "MODIFIED")
    }
    else {
      if (isFirst) Log.i(TAG, "NOOP")
      else Log.i(TAG, "REMOVED")
    }
    

    或者,如果您更喜欢简单的条件列表:

    if ( snapshot.exists() &&  isFirst) Log.i(TAG, "ADDED")
    if ( snapshot.exists() && !isFirst) Log.i(TAG, "MODIFIED")
    if (!snapshot.exists() &&  isFirst) Log.i(TAG, "NOOP")
    if (!snapshot.exists() && !isFirst) Log.i(TAG, "REMOVED")
    

    NOOP 是在基于事件的侦听器中永远不会存在的情况,因为它根本不会有针对这种情况的事件。

    【讨论】:

    • 非常感谢。您的解决方案确实有效。我建议在第二种方法中使用一些“else ifs”。
    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2022-01-21
    • 2019-09-24
    • 2019-02-05
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多