简体   繁体   中英

How to create one stream listening to multiple Firestore documents created from list of documents references in Flutter

Im trying to create one stream, that is using multiple documents references that are stored and fetched from Firebase Firestore.

Lets say I have two collection named users and documents . When user is created he gets document with his id in users collection with field named documentsHasAccessTo that is list of references to documents inside documents collection. It is important, that these documents can be located in different sub collections inside documents collection so I dont want to query whole documents and filter it, in order to save Firestore transfer and make it faster I already know paths to documents stored in documentsHasAccessTo field.

So for example, I can have user with data inside users/<user uid> document with documentsHasAccessTo field that stores 3 different document references.

I would like to achieve something like this (untested):

final userId = 'blablakfn1n21n4109';
final usersDocumentRef = FirebaseFirestore.instance.doc('users/$userId');
usersDocumentRef.snapshots().listen((snapshot) {
    final references = snapshot.data()['documentsHasAccessTo'] as List<DocumentReference>;

    final documentsStream =  // create single query stream using all references from list
});

Keep in mind, that it would also be great, if this stream would update query if documentsHasAccessTo changes like in the example above, hence I used snapshots() on usersDocumentReferences rather than single get() fetch.

The more I think about this Im starting to believe this is simple impossible or theres a more simple and clean solution. Im open to anything.

You could use rxdart 's switchMap and MergeStream :

usersDocumentRef.snapshots().switchMap((snapshot) {
  final references = snapshot.data()['documentsHasAccessTo'] as List<DocumentReference>;
  return MergeStream(references.map(ref) => /* do something that creates a stream */));
});

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