Search code examples
kotlingoogle-cloud-firestorelistener

How to get a DocumentChange object for a single document from Firestore collection in Kotlin?


How can I get a DocumentChange object for a single documentSnapshot? I want to use the type of the document's change inside my when statement. It is easy with querySnapshot, but I do not know how to get around this for a listening to changes on a single document.

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


Solution

  • You don't get a DocumentChange.Type when listening for a single document. Instead you get a DocumentSnapshot that contains the state for that document.

    You can derive what happened from looking at the document, and keeping track whether this is the first callback to your listener:

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

    Or if you prefer a flat list of conditions:

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

    The NOOP is a case that would never exist in the event based listeners, as it simply wouldn't have an event for that situation.