Multiple StreamBuilder using a static Stream and associated firebase reads cost?

50 views Asked by At

For a single app instance (i.e. one user running a flutter web app), what would be the number of reads for the below example?

My app has firestore as database where a collection has 10 docs. I have created a static stream like below in a class named MyWidgetClass.

static Stream<List<MyData>> readJobs() async* {
    var stream = FirebaseFirestore.instance
        .collection('jobs')
        .where("timeline.start_dt",
            isGreaterThan: DateTime.now().subtract(Duration(days: numPastDays)))
        .snapshots()
        .map((snapshot) => snapshot.docs.map((doc) => MyData.fromMap(doc)).toList());
    await for (final snapshot in stream) {
      yield snapshot;
    }
  }

Then, two other widgets (2 other separate classes), listens to the same stream including MyWidgetClass where stream was defined as below:

  Stream<List<MyData>>? jobStream;
  late StreamSubscription _jobStreamSubscription;

  stream() {
    _jobStreamSubscription = jobStream!.listen((event) {
      jid = event.map((e) => {e.jid: e.jobDetail.client_uid}).toList();
    });
  }

  @override
  void initState() {
    jobStream = MyWidgetClass.readJobs();
    stream();
    super.initState();
  }

Does Firebase consider these three different class as separate listeners and read count equals 30, or read count will still be 10?

1

There are 1 answers

4
Doug Stevenson On

Your code is showing only a single query, which means there is only one listener here for each time readJobs is invoked. If you invoke readJobs once, you will have one listener with one set of results being billed. If you decide to share the resulting data with other parts of your code, that doesn't change the behavior or cost of that one query - the Stream isn't going to do anything extra on Firestore to add costs.