飞镖/颤振 - 回调函数内的"yield"



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

我的问题与这里解决的问题非常相似:Dart 组件:如何返回异步回调的结果? 但我无法使用完成器,因为我需要屈服而不是返回。

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

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来处理外部函数中的事件。

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

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;
}
}

我想在这里添加改进建议。在某些情况下,应避免使用建议的await for解决方案,因为它是不可关闭的侦听器,并且会停止侦听,因此这可能会导致内存泄漏。您也可以使用.map来转换流生成结果,如下所示(尚未尝试编译它,但主要思想应该很清楚):

Stream<List<EventModel>> fetchEvents() { // remove the async*
Firestore.instance
.collection('events')
.getDocuments()
.asStream()
.map((snapshot) { // use map instead of listen
List<EventModel> list = List();
snapshot.documents.forEach((document) {
list.add(EventModel.fromJson(document.data));
});
return list; // use return instead of yield
});
}

最新更新