How to wait for multiple Firestore Streams to return Data in Flutter
194
For that check the async package there is a class named StreamGroup, and you can combine N streams on that class writing:
final newStream = StreamGroup.merge([streamOne, streamTwo]);
Then you can use that newStream as a common stream.
Author by
Mete
Updated on December 07, 2022Comments
-
Mete over 1 year
I want to query two Firestore collections, but only want to return the data of the collection which returns a result quicker then the other one.
My approach was to use 2 streams and to wait till one of them gives back data, which I then can return.
I used the onData Parameter, but the compiler never jumps in the onData Method even if there is data in the collections which matches the query.
var someId; CollectionReference collection1 = _db.collection('collection1'); CollectionReference collection2 = _db.collection('collection2'); Query collection1Query = collection1.where('users', arrayContains: uid); Query collection2Query = collection2.where('users', arrayContains: uid); var resultStream1 = collection1Query.snapshots().listen((doc) {}); var resultStream2 = collection2Query.snapshots().listen((doc) {}); while(someId == null){ resultStream1.onData((data) { var someId = data.docs.first.id; }); resultStream2.onData((data) async { var someId = data.docs.first.id; await doOneMoreThing(someId); }); } resultStream1.cancel(); resultStream2.cancel(); return someId;
-
pskink over 3 yearscheck
StreamGroup
/StreamZip
-