2

I have a chat feature that gets Firestore documents for both the current user and the person he/she is chatting with. I'm trying to merge these streams together, but when I use mergeWith or Rx.merge, it only returns the results of one stream. Here is the function that gets the data:

fetchData(String userUid, String chatterUid) async {
var myChats = _messages
    .document(userUid)
    .collection('userMessages')
    .document(chatterUid)
    .collection('chats')
    .orderBy('time', descending: true)
    .snapshots();

var otherChats = _messages
    .document(chatterUid)
    .collection('userMessages')
    .document(userUid)
    .collection('chats')
    .orderBy('time', descending: true)
    .snapshots();

Rx.merge([otherChats, myChats]).listen((event) {
  if (event.documents.isNotEmpty) {
    _controller.add(event.documents.map((e) {
      return Chat.fromData(e.data);
    }).toList());
  } else {
    _controller.add(<Chat>[]);
  }
});

Is there anyway to combine the results so that all the results are filtered into one stream that I can return?

Eric Jubber
  • 131
  • 1
  • 9
  • This question is probably a duplicate to https://stackoverflow.com/questions/51214217/combine-streams-from-firestore-in-flutter . The 2nd answer at that question mentions `Stream stream = StreamGroup.merge([stream1, stream2])`. – josxha Jun 22 '20 at 21:31
  • Does this answer your question? [Combine streams from Firestore in flutter](https://stackoverflow.com/questions/51214217/combine-streams-from-firestore-in-flutter) – josxha Jun 22 '20 at 21:33
  • 3
    `StreamGroup.merge` only returns `stream2` data, not `stream1` data. In other words if I use StreamGroup.merge([streamData1, streamData2]); then returns only streamData2 query records or in vice-versa case StreamGroup.merge([streamData2, streamData1]); returns streamData1 query records which means last query record is returned by StreamGroup.merge function. – Kamlesh Jun 16 '21 at 18:01
  • @Eric Kindly share full of code so that we can understand what is missing to fix this issue? Thanks. – Kamlesh Jun 18 '21 at 18:17

1 Answers1

0

You can try and see if StreamZip fits your use case. It should help manage multiple Streams, and from there you can sort the messages that you'll display into a List.

import 'package:async/async.dart';

Stream<DocumentSnapshot> stream1 = myChats = _messages
    .document(userUid)
    .collection('userMessages')
    .document(chatterUid)
    .collection('chats')
    .orderBy('time', descending: true)
    .snapshots();
Stream<DocumentSnapshot> stream2 = _messages
    .document(chatterUid)
    .collection('userMessages')
    .document(userUid)
    .collection('chats')
    .orderBy('time', descending: true)
    .snapshots();

StreamZip bothStreams = StreamZip([stream1, stream2]);

bothStreams.listen((snaps) {
 DocumentSnapshot snapshot1 = snaps[0];
 DocumentSnapshot snapshot2 = snaps[1];

 // ...
});
Omatt
  • 8,564
  • 2
  • 42
  • 144