firebase / firebase-android-sdk

Firebase Android SDK
https://firebase.google.com
Apache License 2.0
2.27k stars 574 forks source link

FR: Scope Firestore SnapshotListeners to a LifecycleOwner #2539

Open thatfiredev opened 3 years ago

thatfiredev commented 3 years ago

What feature would you like to see?

I would like to be able to scope a Firestore SnapshotListener to a LifecycleOwner the same way we're able to scope a Listener to an Activity:

val query: Query = Firebase.firestore.collection("restaurants")

query.addSnapshotListener(viewLifecycleOwner) { snapshot, error ->
    // do something
}

How would you use it?

1. As Fragment scoped listeners

One of the recommended best-practices on Modern Android Development is to let a single Activity host multiple fragments. It would be nice if we could, for example bind a SnapshotListener to Fragment A, and when we navigate to Fragment B, the listener from A gets removed so we can add a different listener in fragment B.

Note that Fragments provide a [getViewLifecycleOwner()](https://developer.android.com/reference/androidx/fragment/app/Fragment#getViewLifecycleOwner()) method that already allows developers to scope other kinds of listeners (eg. LiveData#observe()) to the [Fragment's View](https://developer.android.com/reference/androidx/fragment/app/Fragment#getView()) lifecycle, which means the listener is automatically removed once the fragment is no longer visible (user navigated away, for example).

2. As custom components scoped listeners

The androidx.lifecycle package allows developers to create custom lifecycle-aware components. With the feature proposed here, developers would be able to easily scope snapshot listenerers to their custom components.

3. To (slightly) improve FirebaseUI-Android?

FirebaseUI has its own implementation of the feature proposed here. It prompts the user to provide a LifecycleOwner, and then removes the snapshot listener when the LifecycleOwner's ON_STOP Event is called:

https://github.com/firebase/FirebaseUI-Android/blob/71bfba25b3b1c9fdcfcf1dc20278d82da479bf44/firestore/src/main/java/com/firebase/ui/firestore/FirestoreRecyclerAdapter.java#L55-L62

With this feature, FirebaseUI (and other apps or libraries that followed that same approach) will no longer need their own implementation and would be able to rely on the one offered by the first-party SDK.

thatfiredev commented 3 years ago

I've opened a PR trying to implement this feature, please see #2541

wu-hui commented 3 years ago

Thank you very much! Please see the comment I left in the PR.