Categories
Development

Combine streams with rxdart to be used in a single StreamBuilder

For several days I tried to find an answer for this question.
Many examples are confusing for me, and I really don’t understand how to implement them using rxdart, despite they look so simple.

I’m trying to combine 4 collections from Firestore to be used in a single StreamBuilder.

Observable<QuerySnapshot> firstList = Firestore.instance.collection(bla).snapshots();

Observable<QuerySnapshot> secondList = Firestore.instance.collection(blabla).snapshots();

Observable<QuerySnapshot> thirdList= Firestore.instance.collection(blablabla).snapshots();

Observable<QuerySnapshot> fourthList= Firestore.instance.collection(blablablabla).snapshots();

LATEST EDIT
I’ve changed from Observable to Stream like it was before I’ve tried using rxdart.

Stream<QuerySnapshot> firstList = Firestore.instance.collection(bla).snapshots();

Stream<QuerySnapshot> secondList = Firestore.instance.collection(blabla).snapshots();

Stream<QuerySnapshot> thirdList= Firestore.instance.collection(blablabla).snapshots();

Stream<QuerySnapshot> fourthList= Firestore.instance.collection(blablablabla).snapshots();

And I’m using rxdart to combine them:

Observable<SomeList> allList = Observable.combineLatest4(
        firstList,
        secondList,
        thirdList,
        fourthList, (a, b, c, d) => SomeList(a, b, c, d));

Here is the class I’m using above:

class SomeList{
  QuerySnapshot firstList;
  QuerySnapshot secondList;
  QuerySnapshot thirdList;
  QuerySnapshot fourthList;

  SomeList(this.firstList, this.secondList, this.thirdList,
      this.fourthList);
}

Inside the build method I’m returning a StreamBuilder as follows:

Widget build(BuildContext context) {
    return Scaffold(
        appBar: _bla(),
        body: SingleChildScrollView(
        child: Column(
            children: <Widget>[
                return new StreamBuilder(
                    stream: allList, // here is my main issue
                    ...
                    ),
                ]
            ),
        ),  
    );
}   

When I run the code I get an exception:

Class 'SomeList' has no instance getter 'documents'.
Receiver: Instance of 'SomeList'
Tried calling: documents

type '_BroadcastStream<QuerySnapshot>' is not a subtype of type 'Observable<QuerySnapshot>'

So I tried to remove the calling of asBroadcastStream() when initializing allList, but the error is the same.

I’ve looked into these examples before posting my issue:
Update streams based on filters in Dart/Flutter
Merge Firestore streams using rxDart
https://www.burkharts.net/apps/blog/rxdart-magical-transformations-of-streams/
https://medium.com/@ayushpguptaapg/using-streams-in-flutter-62fed41662e4

What is the proper way to combine these streams into a single stream, and then be used in a StreamBuilder?
Could you please give a small example?

Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *