Wilfred Almeida
Wilfred Almeida

Reputation: 651

Firebase Firestore reads on streams

I am using Firestore stream in my flutter app. The data is user profiles so I need to filter it as needed. My initial data stream is as follows

Stream s = FirebaseFirestore.instance
        .collection('users')
        .snapshots(includeMetadataChanges: true);

and when I have to filter data, I do

setState((){

s = FirebaseFirestore.instance
        .collection('users')
        .where('name',isEqualTo:"MyName")
        .snapshots(includeMetadataChanges: true);

});

This works fine but my concern is reads, I know that data is cached and is read from server only if something changes but I don't know of streams.

I tried monitoring the usage on firebase but due to the app being in production I couldn't measure anything properly.

And if filtering by changing stream does cause reads on firebase then what else can I do to filter data from cache.

One thing I thought off was storing everything locally but storing data of thousands of users locally is impractical.

Upvotes: 0

Views: 1434

Answers (1)

TobyLoby
TobyLoby

Reputation: 342

A stream is a sequence of asynchronous events. It is like an asynchronous Iterable—where, instead of getting the next event when you ask for it, the stream tells you that there is an event when it is ready. From Dart (https://dart.dev/tutorials/language/streams)

A stream is a continues datastream that closes when the class is terminated or by canceling the stream object:

streamSub.cancel();

You can use a stream in a streambuilder. Every time a change is applied to any of the documents, it rebuilds the builder.

StreamBuilder(
   stream: stream,
   builder: (BuildContext content, AsyncSnapshot snapshot) {
   }
)

If 1 document changes in query results, you will be billed 1 read. You are not billed for documents that are unchanged. The query snapshot object merely reuses the document data that was in memory from the prior set of results. By Doug Stevenson (https://stackoverflow.com/a/60062304/9142870)

Upvotes: 1

Related Questions