Cavid Cavidd
Cavid Cavidd

Reputation: 1

Firestore reduce reads

I want to reduce reading from FireStore. if, when a new data is added, it should only fetch that data. I don't want it to read the whole database again. I think this would be unnecessary and costly. I tried the code below but it doesn't work, it doesn't pull any data

https://medium.com/firebase-tips-tricks/how-to-drastically-reduce-the-number-of-reads-when-no-documents-are-changed-in-firestore-8760e2f25e9e

    query.get(CACHE).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                boolean isEmpty = task.getResult().isEmpty();
                if (isEmpty) {
                    query.get(SERVER).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
                                Item item= documentSnapshot.toObject(Item.class);
                                items.add(item);
                                adapter.notifyDataSetChanged();
                            }

                        }
                    });
                }
                }
        }
    });

And when i try other method, reads data in memory when offline but reloads all database when online. thank you in advance for any of suggestions.

                query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                         for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
                                Item blogPost = doc.getDocument().toObject(Item.class);
                                items.add(blogPost);
                                mAdapter.notifyDataSetChanged();
                         }
                        
                    }
                });

Upvotes: 0

Views: 169

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

When you are using a get() call, you are always getting the online version of the documents from the Firebase servers. If you only want to get what's new, you should consider tracking the changes between snapshots. In this way, you can get only the data the corresponds to a specific operation.

But remember that there is no way you can skip the initial data. I have answered a question regarding this topic too:

Upvotes: 1

Related Questions