flutter firestore等待查询快照流首先返回旧值,然后更新为新值

问题描述 投票:0回答:1

我正在使用 flutter 和 firestore 数据库,尝试构建一个时间范围查询以从 firestore 返回数据流。我看到的行为很奇怪,我运行查询,得到旧的查询结果,几秒钟后,我得到新查询结果的流更新。我使用

await for
的目的是等待流完成。

这是我的查询快照流 - 存储库代码:

Stream<QuerySnapshot> packagesColStream = query.snapshots();
print('built query - sent');
await for (QuerySnapshot e in packagesColStream) {
    print('awaiting for stream');
    List<Package> packagesList = [];
    for (var doc in e.docs) {
      var data = doc.data() as Map<String, dynamic>;
      Package package = Package.fromDocument(data);
      if (filterFunction != null) {
        if (!filterFunction(package)) {
          continue;
        }
      }
      packagesList.add(package);
    }
    print('built list - yielding');
    yield packagesList;
}

处理收益的代码:

print('on GetStoreGroupingPackagesEvent');
Stream<List<Package>> packagesStream = packagesRepo.getPackagesStream(
      event.fromDate,
      event.endDate,
);
await for (List<Package> packagesList in packagesStream) {
print('got stream from repository');
var groupedStores =
          groupBy(packagesList, (element) => element.storeID);
List<PackageGroup> packagesGroups = groupedStores.values
          .map(
            (e) => PackageGroup(
              groupKey: Store(
                id: e[0].storeID,
                name: e[0].storeName,
                // proprietorshipNumber: e[0].storePS,
                phoneNumber: e[0].ownerPhone,
                address: '',
                email: '',
                imageURL: '',
              ),
              packagesList: e,
            ),
          )
          .toList();
print('returning grouped by stream');
emit(PackagesGroupingState.loaded(packageGroupsList: packagesGroups));
 

打印输出:

applyting  filter
on GetStoreGroupingPackagesEvent
built query - sent
state is PackagesGroupingStatus.loading
awaiting for stream
built list - yielding
got stream from repository
returning grouped by stream
state is PackagesGroupingStatus.loaded
awaiting for stream
built list - yielding
got stream from repository
returning grouped by stream
state is PackagesGroupingStatus.loaded 

请注意,“等待流”打印了两次,第一个返回了我拥有的旧数据,第二个返回了正确的数据。

为什么会出现这样的行为?为什么await for并不是真正在等待流?

flutter firebase google-cloud-firestore
1个回答
0
投票

显然,实际发生的情况是 firestore 首先从缓存中获取适合查询的数据,然后才从 firestore 中获取其余数据。

因此,如果新查询在原始查询之上只有更多数据,那么它只会在从缓存中获取所有数据后传输其余数据。

© www.soinside.com 2019 - 2024. All rights reserved.