【问题标题】:Subscribe to a stream and forward it in flutter dart订阅流并在颤振飞镖中转发
【发布时间】:2021-04-25 06:07:07
【问题描述】:

我使用firestore 订阅这样的流:

db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
  // something
});

listen 返回一个StreamSubscription<QuerySnapshot>

现在我想写一个方法,订阅这个流,这样当我得到新结果时我可以做一些事情。但是同样的方法应该自己返回一个数据流。我试过这个:

static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
    db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
      // do something and now forward incoming snapshot
      yield snapshot;
    });
  }

这不起作用,因为 yield 在内部上下文中甚至都不知道。我怎样才能做到这一点?非常感谢!

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore dart-stream


    【解决方案1】:

    测试,工作

    static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
        var stream = db.collection(collection).snapshots();
        await for(final snapshot in stream){
            yield snapshot;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以映射和转换流然后返回它:

      static Stream<QuerySnapshot> listenOnCollection(String collection){
        return db.collection(collection).snapshots().map((QuerySnapshot snapshot) {
           // do something and now forward incoming snapshot
           return snapshot;
        });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-12
        • 2020-11-05
        • 2020-09-12
        • 2020-12-25
        • 2020-05-12
        • 1970-01-01
        • 2020-05-19
        • 2023-03-05
        相关资源
        最近更新 更多