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 Fragment
val docRef = ...

docRef.addSnapshotListener(this) { documentSnapshot, firebaseFirestoreException ->
    // do something
}

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

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.