[英]How to combine to different firebase query streams into one stream?
[英]How to combine streams into one stream in flutter properly?
由于WHERE IN Query ,我正在尝试组合来自Cloud Firestore
的多个流。 此查询的一个缺点是它在一个查询中仅限于 10 个值。 但是我有一个包含超过 10 个值的列表,所以我在一个WHERE IN query
中从该列表中查询每 10 个值,并将结果作为Stream<List<Product>>
。 所以最后我想将所有查询中的所有流合并到一个Stream<List<Product>>
并从我的 function 中返回该Stream<List<Product>>
。
这是我正在使用的代码:
Stream<List<Product>> cartProductsStream(List<List<int>> idGroupList) {
// idGroupList = [[1,2,3,4,5,6,7,8,9,10], [11,12,13,14,15]];
// here I am querying from firestore for every list from idGroupList.
for (List<int> listOfTen in idGroupList) {
Stream<List<Product>> resultList = _db
.collection('products')
.where('id', whereIn: listOfTen)
.snapshots()
.map((event) => event.documents
.map((e) => Product.fromJson(
e.data,
))
.toList());
}
}
从这里我想将每个resultList
合并到一个 stream 并返回 stream。 我怎样才能做到这一点? 提前致谢。
更新
它可能对谁感兴趣。 在@pskink 和@EdwardLi 的指导下,我解决了这样的问题:
我的 function 用于流:
List<Stream<List<Product>>> cartProductsStream(List<List<int>> idGroupList) {
// idGroupList = [[1,2,3,4,5,6,7,8,9,10], [11,12,13,14,15]];
List<Stream<List<Product>>> streamList = [];
for (List<int> listOfTen in idGroupList) {
Stream<List<Product>> resultList = _db
.collection('products')
.where('id', whereIn: listOfTen)
.snapshots()
.map((event) => event.documents
.map((e) => Product.fromJson(
e.data,
))
.toList());
streamList.add(resultList);
}
return streamList;
}
我的StreamBuilder
小部件:
StreamBuilder(
stream: CombineLatestStream.list(stream.cartProductsStream(
idList.toList())), // to combine streamList into one. return type List<List<Product>>
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: LoadingPage(),
);
}
// here snapshot data is List<List<Product>> type. so in this for loop i add all List<Product> into one
for (List<Product> fbList in snapshot.data) {
fbProducts.addAll(fbList.toSet());
}});
您可以使用空列表并添加元素
Stream<List<Product>> cartProductsStream(List<List<int>> idGroupList) {
List<Product> returnProducts = [];
// idGroupList = [[1,2,3,4,5,6,7,8,9,10], [11,12,13,14,15]];
// here I am querying from firestore for every list from idGroupList.
for (List<int> listOfTen in idGroupList) {
Stream<List<Product>> resultList = _db
.collection('products')
.where('id', whereIn: listOfTen)
.snapshots()
.map((event) => event.documents
.map(
(e) => returnProducts.add(
Product.fromJson(e.data)
)
));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.