'Flutter - Issue with using single Stream.asBroadcast() on multiple StreamBuilders

I have an app which has a single stream of data coming from firestore

static Stream<List<StudyGoal>> streamStudyGoals(
      {required String fromUserId}) {
    var ref = _database
        .collection(AppConfig.firestoreUsersIdentifier)
        .doc(fromUserId)
        .collection(AppConfig.firestoreStudyGoalsIdentifier);

    return ref.snapshots().map((list) =>
        list.docs.map((doc) => StudyGoal.fromMap(data: doc.data())).toList());
  }

I have an "app database" which creates a new stream using the code above. Note that I am creating it as a broadcast stream

class AppDatabase {
  AppDatabase._privateConstructor();

  static final AppDatabase _instance = AppDatabase._privateConstructor();

  factory AppDatabase() {
    return _instance;
  }

  //Global
  final studyGoalsStream = FirestoreManager.streamStudyGoals(
          fromUserId: FirebaseAuthManager.getCurrentUser().uid)
      .asBroadcastStream();
}

Now I have 2 StreamBuilders on seperate pages that both use this same stream that is created above.

StreamBuilder #1

Widget buildStudyGoalsStream() => StreamBuilder<List<StudyGoal>>(
      stream: appDatabase.studyGoalsStream,
      builder: ...);

StreamBuilder #2

StreamBuilder<List<StudyGoal>>(
            stream: appDatabase.studyGoalsStream,
            builder: ...)

The undesired result I get is that the StreamBuilder which was built after the other gets stuck on ConnectionState.waiting (the one that gets built first works fine). It appears that only one of these two StreamBuilders are able to use this stream correctly.

So, as a clarification

Produces undesired results:

StreamBuilder #1
    stream: appDatabase.studyGoalsStream,

StreamBuilder #1
    stream: appDatabase.studyGoalsStream,

Works perfectly (but creates two seperate streams):

StreamBuilder #1
        stream: FirestoreManager.streamStudyGoals(
          fromUserId: FirebaseAuthManager.getCurrentUser().uid),

    StreamBuilder #1
        stream: FirestoreManager.streamStudyGoals(
          fromUserId: FirebaseAuthManager.getCurrentUser().uid),

Any ideas???



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source