简体   繁体   中英

How to attach a permanent listener to a Firestore query?

I'm trying to implement pagination in Firestore. I have created an EventListener object like so:

EventListener<QuerySnapshot> listener = (querySnapshot, e) -> {
    if (e != null) return;

    for (DocumentChange documentChange : querySnapshot.getDocumentChanges()) {
        //Get data
    }
    lastVisible = querySnapshot.getDocuments().get(querySnapshot.size() - 1);
};

I also have a Query like so:

Query query = usersRef.orderBy("name", ASCENDING).limit(4);

In my onCreate I do this:

query.addSnapshotListener(MainActivity.this, listener);

To implement pagination in my RecyclerView, I use:

RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {}

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        query = query.startAfter(lastVisible);
        query.addSnapshotListener(MainActivity.this, listener);
    }
};
recyclerView.addOnScrollListener(onScrollListener);

Meaning that when the user reaches the limit, I want to load next users. However, I don't get the right indexes. According to Frank van Puffelen's answer , I'm using multiple listeners, which is indeed what I'm doing, since I'm using query.addSnapshotListener() twice. My question is, how to replace the first query, with the second one without attaching a new listener? How to always use the same listener?

It's not possible to simply replace the query for a listener. When you add a listener to a query, it will forever use that query until the listener is removed.

If you want to start getting results for a new query, you will have to repeat the process and add a listener to that new query. You can use the same listener object if you want, but you can't simply "swap in" a new query.

My advice to pagination is using local database as the layer between your remote data and your app. The idea is, get the data into your database, which you can have absolute control in paginating the data. For example, when you need the data, query your database, if the query doesn't exists, query your firebase, cache the data to your database which will in turn feed your request. That is the flow. If you don't understand you can ask me.

PS: this is just an advice, not an answer to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM