飞镖/颤振-“产量”在回调函数中 [英] Dart/Flutter - "yield" inside a callback function

查看:89
本文介绍了飞镖/颤振-“产量”在回调函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要产生一个函数列表;但是,我想从回调函数中产生列表,该回调函数本身在主函数内部-这导致yield语句不是针对主函数执行,而是针对回调函数执行。

I need to yield a list for a function; however, I want to yield the list from within a callback function, which itself is inside the main function - this results in the yield statement not executing for the main function, but rather for the callback function.

我的问题与此处解决的问题非常相似: Dart组件:如何返回异步回调的结果?,但是我不能使用Completer,因为我需要屈服而不返回。

My problem is very similar to the problem that was solved here: Dart Component: How to return result of asynchronous callback? but I cannot use a Completer because I need to yield and not return.

以下代码应该更好地描述问题:

The code below should describe the problem better:

Stream<List<EventModel>> fetchEvents() async* { //function [1]
    Firestore.instance
        .collection('events')
        .getDocuments()
        .asStream()
        .listen((snapshot) async* { //function [2]
      List<EventModel> list = List();
      snapshot.documents.forEach((document) {
        list.add(EventModel.fromJson(document.data));
      });

      yield list; //This is where my problem lies - I need to yield for function [1] not [2]
    });
  }


推荐答案

而不是 .listen 处理另一个函数内部的事件,您可以使用 await for 处理外部函数内部的事件。

Instead of .listen which handles events inside another function you can use await for to handle events inside the outer function.

另外-当生成 List 实例仍在内部流回调中填充时,您可能想重新考虑该模式...

Separately - you might want to reconsider the pattern when you yield List instances that are still getting populated inside an inner stream callback...

Stream<List<EventModel>> fetchEvents() async* {
  final snapshots =
      Firestore.instance.collection('events').getDocuments().asStream();
  await for (final snapshot in snapshots) {
    // The `await .toList()` ensures the full list is ready
    // before yielding on the Stream
    final events = await snapshot.documents
        .map((document) => EventModel.fromJson(document.data))
        .toList();
    yield events;
  }
}

这篇关于飞镖/颤振-“产量”在回调函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆