我正在尝试在我的服务中测试流事件,并遇到一个问题:是否有任何方法可以在异步流中同步传递事件?这是简化的代码示例:
test("deliver event", () {
StreamController sc = new StreamController();
String v = "old";
sc.stream.listen((val) {v = val;});
sc.add("new");
expect(v, "new"); // test fails: actual value is "old"
});
答案 0 :(得分:1)
您无法从异步到同步进行任何操作。
import 'dart:async';
Future main() async {
StreamController sc = new StreamController();
String v = "old";
var subscr = sc.stream.listen((val) { v = val;});
sc.add("new");
subscr.asFuture().then((_) {
print('assert v == "new": ${v == 'new'}');
// expect(v, "new"); // test fails: actual value is "old"
});
sc.close();
}