Search code examples
flutterfirebasedartgoogle-cloud-firestorestream

Subscribe to a stream and forward it in flutter dart


I use firestore to subscribe on a stream like this:

db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
  // something
});

The listen returns a StreamSubscription<QuerySnapshot>

Now I want to write a method, that is subscribing to this stream so I can do something when I get new results. But the same method should return a stream of this data on its own. I tried this:

static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
    db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
      // do something and now forward incoming snapshot
      yield snapshot;
    });
  }

This won't work as yield is not even known in the inner context. How can I achieve this? Thanks alot!


Solution

  • Tested, working

    static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
        var stream = db.collection(collection).snapshots();
        await for(final snapshot in stream){
            yield snapshot;
        }
    }