Firestore addSnapshotListener Once Only (get vs addSnapshotListener) (Android/Kotlin)

Apr 8, 2019
val docRef = ...var registration: ListenerRegistration? = nullregistration = docRef    .addSnapshotListener { doc, e ->        registration?.remove()    }

Kotlin extension

fun DocumentReference.addSnapshotListenerOnce(listener: (DocumentSnapshot?, FirebaseFirestoreException?) -> Unit): ListenerRegistration {    val registration = addSnapshotListener(listener)    addSnapshotListener { doc, e ->        listener(doc, e)        registration.remove()    }    return registration}

NOTE: The downside of this implementation is that if local cache copy differ from server, removing listener after once shall not get the lastest copy from server.

DocumentReference get vs addSnapshotListener (Once) behaviour.

  • get by default will make a network call/check (slow)
  • You can use Source.CACHE with get to get a local cache copy (fast). If local cache is not available, an error shall be returned (and won't get from server).
  • addSnapshotListener will return a local cache copy immediately when available. It local cache copy not available, it will get from the server.

NOTE: Refer to Firestore DocumentReference Get Local First (fall back to Server if cache doesn't exist).

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.