我在 Firebase Firestore DB 中有以下数据库结构:
Doc business
-> Col delivery_plan
-> Doc delivery_plan
-> Col delivery_point
-> Doc delivery_point
(见{{3 }})
我需要的是从 delivery_plan
集合(基于查询)中获取文档子集及其子集合中的所有文档 delivery_point
和不断变化。
在我的 flutter 应用程序中,我有一个模型类 DeliveryPlanList
,我希望每次发生任何变化时都返回它的实例(查询 delivery_plan
或任何 delivery_point
中的任何文档)< /p>
我尝试的是使用 database structure 包组合流,这样我就不需要为每个 delivery_plan
文档打开和关闭 StreamSubscriptions:
Stream<DeliveryPlanList> deliveryPlanListStream(
String businessId,
Set<DeliveryPlanStatus> statuses,
DateTime date,
) {
return FirebaseFirestore.instance
.collection('business')
.doc(businessId)
.collection('delivery_plan')
.where('date', isEqualTo: DateFormat('yyyy-MM-dd').format(date))
.where('status', whereIn: statuses.map((s) => enumToString(s)).toList())
.snapshots()
.flatMap((s) {
var innerStreams = s.docs.map((e) => deliveryPlanStream(businessId, e.data()['id']));
return CombineLatestStream(innerStreams,
(List<DeliveryPlan> planList) => DeliveryPlanList(deliveryPlans: planList, lastUpdated: DateTime.now()));
});
}
Stream<DeliveryPlan> deliveryPlanStream(String businessId, String deliveryPlanId) {
Stream<DocumentSnapshot> planStream = FirebaseFirestore.instance
.collection('business')
.doc(businessId)
.collection('delivery_plan')
.doc(deliveryPlanId)
.snapshots();
Stream<QuerySnapshot> pointsStream = FirebaseFirestore.instance
.collection('business')
.doc(businessId)
.collection('delivery_plan')
.doc(deliveryPlanId)
.collection('delivery_point')
.snapshots();
return CombineLatestStream.combine2(planStream, pointsStream,
(planSnapshot, pointsSnapshot) => DeliveryPlan.fromFirebase(planSnapshot, pointsSnapshot));
}
但是,我并不完全理解 flatMap
的作用,因为当我关闭 deliveryPlanListStream(...)
的订阅时,流似乎从未关闭。当我切换业务、关闭 StreamSubscriptions 并开始一个新的业务时可以看到这一点,其功能与我的 BLoC 中的功能相同:
_deliveryPlansStream?.cancel();
_deliveryPlansStream =
GetIt.I<DeliveryRepository>().deliveryPlanListStream(businessId, statuses, date).listen((snapshot) {
this.add(UpdateDeliveriesEvent(snapshot));
});
监听这些数据变化的最佳方式是什么? 谢谢!