简体   繁体   中英

Concanete 2 firestore QuerySnapShot streams in dart-flutter by RxDart

My Flutter project has a StreamBuilder widget. It listens firestore querysnapshot stream . If I use only one query stream there is no problem, every things works as I expected. But, if I concatenate 2 streams, then it listen only first stream. I think, stream1 not emits all data therefore stream2 is not appended to result stream. But I don't know how can I achieve this problem.

I appreciate any help. thanks.

Stream<List<MyLog>> myLogStream() {
    Stream<QuerySnapshot> stream1 = Firestore.instance
        .collection('devicelog/1/mylog')
        .snapshots();
    Stream<QuerySnapshot> stream2 = Firestore.instance
        .collection('devicelog/2/mylog')
        .snapshots();
    return Rx.concat([stream1, stream2]).map((qShot) => qShot.documents
        .map((doc) => MyLog.fromCloud(doc.documentID, doc.data))
        .toList());
}

Concat waits to subscribe to each additional Observable that you pass to it until the previous Observable completes.

concat will not read stream2 until stream1 has completes

Concat will not see, and therefore will not emit, any items that Observable emits before all previous Observables complete

that's why it listens only to the first stream. because it has to complete the first stream before moving to the next one and by then it's too late because stream2 has already emitted some items source

what you are probably looking for is Rx.combineLatest so you combine each object emitted by stream1 stream2 into one object that gets emitted to stream3

Stream<List<MyLog>> myLogStream() {
  Stream<QuerySnapshot> stream1 =
      Firestore.instance.collection('devicelog/1/mylog').snapshots();
  Stream<QuerySnapshot> stream2 =
      Firestore.instance.collection('devicelog/2/mylog').snapshots();
  return Rx.combineLatest2(stream1, stream2,
      _fun_That_Combines_Each_Object_From_stream1_And_stream2);
}

QuerySnapshot _fun_That_Combines_Each_Object_From_stream1_And_stream2(
    QuerySnapshot mylog1, QuerySnapshot mylog2) {
      // do some magic
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM