Skip to content

FR: Scope Firestore SnapshotListeners to a LifecycleOwner #2539

Open
@thatfiredev

Description

@thatfiredev

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() method that already allows developers to scope other kinds of listeners (eg. LiveData#observe()) to the Fragment's View 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.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions