[英]How to yield inside firebase listener inside stream
Using AngularDart and Firebase, the below code doesn't work because yield
is inside an anonymous inner class. 使用AngularDart和Firebase,下面的代码不起作用,因为
yield
在匿名内部类内部。 How might I rewrite this? 我该如何重写? I'm new to both Angular and Dart and couldn't find any examples for this.
我是Angular和Dart的新手,因此找不到任何示例。
Essentially I'm trying to listen for items inside a stream in my service, but I'm getting the actual item from firebase and need to pass these firebase items back to the stream. 本质上,我试图在我的服务中侦听流中的项目,但是我正在从Firebase获取实际项目,并且需要将这些Firebase项目传递回该流。
In the service: 在服务中:
Stream<Item> itemStream() async* {
final ref = database().ref("items");
await ref.onChildAdded.listen((e) {
DataSnapshot snapshot = e.snapshot;
Map parsedMap = snapshot.val();
String id = snapshot.key;
String property1 = parsedMap['property1'];
String property2 = parsedMap['property2'];
print(property1);
print(property2);
yield new Item(id, property1, property2); // invalid; yield does not work here.
});
// yield works here but it's no use here.
}
Component: 零件:
var stream = itemListService.itemStream();
await for (var item in stream) {
print(item.id);
}
Update: I got around this by not using a service. 更新:我通过不使用服务来解决此问题。 However I thought using a service was better practice so that's why I wanted to do it.
但是我认为使用服务是更好的做法,所以这就是为什么我想要这样做。
You could do two things. 您可以做两件事。
1) Use a StreamController
1)使用
StreamController
2) (Better) 2)(更好)
Stream<Item> itemStream() { final ref = database().ref("items"); return ref.onChildAdded.map((e) { DataSnapshot snapshot = e.snapshot; Map parsedMap = snapshot.val(); String id = snapshot.key; String property1 = parsedMap['property1']; String property2 = parsedMap['property2']; print(property1); print(property2); return new Item(id, property1, property2); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.