firebase / firebase/firebase-android-sdk
FR: Scope Firestore SnapshotListeners to a LifecycleOwner
- Dominant language
- Java
- Stars
- 2.6k
- Forks
- 710
- Avg merge
- 2d 23h
- Merged PRs (30d)
- 34
Description
## What feature would you like to see?
I would like to be able to scope a Firestore SnapshotListener to a [LifecycleOwner](https://developer.android.com/reference/androidx/lifecycle/LifecycleOwner) the same way we're able to scope a Listener to an [Activity](https://developer.android.com/reference/android/app/Activity):
```kotlin
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](https://developer.android.com/guide/navigation/navigation-getting-started).
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()](https://developer.android.com/reference/androidx/lifecycle/LiveData#observe(androidx.lifecycle.LifecycleOwner,%20androidx.lifecycle.Observer%3C?%20super%20T%3E))) 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](https://developer.android.com/reference/androidx/lifecycle/package-summary) package allows developers to [create custom lifecycle-aware components](https://developer.android.com/topic/libraries/architecture/lifecycle).
With the feature proposed here, developers would be able to easily scope snapshot listenerers to their custom components.
### 3. To (slightly) improve [FirebaseUI-Android](https://github.com/firebase/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.
Contributor guide
Assessment
This issue has not been assessed yet.