【问题标题】:Flutter - Does a stream only read new documents?Flutter - 流是否只读取新文档?
【发布时间】:2020-07-31 15:28:39
【问题描述】:

例如,如果我有一个 QuerySnapshot 类型的 Stream 订阅文档集合,现在将新文档添加到集合中,Stream 是只读取新文档还是重新读取整个文档收藏?

【问题讨论】:

    标签: flutter google-cloud-firestore stream


    【解决方案1】:

    我想这就是你要问的。如果您订阅了 Stream 并获得了 StreamQuerySnapshots,您可以选择在每次添加或更改新文档时重新加载整个数据库,或者只获取新文档。

    //Just gets new documents
    StreamBuilder<QuerySnapshot>(
              stream: Firestore.instance.collection(//Collection).snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> asyncSnapshot) {
                if (asyncSnapshot.hasData) {
                       //This is the difference
                  List<DocumentChange> snapshot =
                      asyncSnapshot.data.documentChanges;
                  snapshot.forEach((DocumentChange change) {}
    
    //Get all documents
    StreamBuilder<QuerySnapshot>(
              stream: Firestore.instance.collection('Test').snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> asyncSnapshot) {
                if (asyncSnapshot.hasData) {
                     //This is the difference
                  List<DocumentSnapshot> snapshot =
                      asyncSnapshot.data.documents;
                  snapshot.forEach((DocumentSnapshot snapshot) {
    

    DocumentChange
    自上次快照以来更改的文档数组。如果这是第一个快照,所有文档都将在列表中作为已添加更改。

    DocumentSnapshot
    每次添加或更改新文档时获取所有文档的列表.

    请记住,就像@Doug Stevenson 所说的,您需要为每个添加或更改的文档付费。

    【讨论】:

    • 所以使用 documentChanges 仅出于性能目的,就文档读取而言,这两个选项没有区别,对吧?
    • 使用 DocumentChange 会减少文档读取次数,因为您只阅读新的或更新的文档
    • 是的,但我没有很好地表达自己,我的意思是:如果您想显示集合中的所有文档并在流开始时获取所有文档,请将其添加到指定列表并通过它到一个显示小部件,然后如果集合中的 smth 发生变化:对于每个 DocumentChange,您将添加/替换/删除指定列表中的文档。这可能会提高性能,但在读取方面不会有所不同。
    • 您必须处理大量文档才能真正注意到性能提升,但您的逻辑是正确的,更少的文档需要处理,因此需要处理的计算更少。
    【解决方案2】:

    每个新添加或更改的文档都需要再次阅读。

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 1970-01-01
      • 2023-03-14
      • 2021-04-20
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多