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.