Firestore addSnapshotListener with LifecycleOwner - Kotlin, Android

May 13, 2019

Kotlin extension

fun Query.addSnapshotListener(lifecycleOwner: LifecycleOwner, listener: (QuerySnapshot?, FirebaseFirestoreException?) -> Unit) {    val registration = addSnapshotListener(listener)    lifecycleOwner.lifecycle.addObserver(object : LifecycleObserver {        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)        fun onDestroy() {            registration.remove()            lifecycleOwner.lifecycle.removeObserver(this)        }    })}fun DocumentReference.addSnapshotListener(owner: LifecycleOwner, listener: (DocumentSnapshot?, FirebaseFirestoreException?) -> Unit): ListenerRegistration {    val registration = addSnapshotListener(listener)    owner.lifecycle.addObserver(object : LifecycleObserver {        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)        fun onDestroy() {            registration.remove()            owner.lifecycle.removeObserver(this)        }        /*        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)        fun onStop() {        }         */    })    return registration}

Usage

val lifecylerOwner = ... // Activity or Fragmentval docRef = ...docRef.addSnapshotListener(this) { documentSnapshot, firebaseFirestoreException ->    // do something}

NOTE: Refer to Android Firestore Document addSnapshotListener as LiveData or Android Firestore Query addSnapshotListener as LiveData.

❤️ 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.