Rid*_*Sun 6 asynchronous dart flutter
我正在使用流读取块中的位置数据。我有一个开始和一个停止事件。在 stop 方法中,我取消了流订阅。当我使用listen流到yield状态时,yield永远不会调用语句的内部。
Stream<LocationState> _start() async* {
_locationSubscription = location.onLocationChanged.listen(
(location) async* {
if (location.isNotNull) {
yield LocationState.sendData(location: updateLocation(location));
}
},
);
//send one initial update to change state
yield LocationState.sendData(
location: updateLocation(await Location().getLocation()));
}
Stream<LocationState> _stop() async {
await _locationSubscription?.cancel();
_locationSubscription = null;
yield LocationState.stoped();
}
Run Code Online (Sandbox Code Playgroud)
当我替换listento 时,await for我看不到任何方法可以阻止它产生事件,因为订阅句柄消失了。有任何想法吗?有什么解释吗?
Stream<LocationState> _start() async* {
await for (LocationData location in location.onLocationChanged) {
if (location.isNotNull) {
yield LocationState.sendData(location: updateLocation(location));
}
}
//send one initial update to change state
yield LocationState.sendData(
location: updateLocation(await Location().getLocation()));
}
Run Code Online (Sandbox Code Playgroud)
问题是我没有完全理解yield的行为。此外,dart 框架也有一些缺点。
此处与飞镖制造商详细讨论了该问题。
https://github.com/dart-lang/sdk/issues/42717
和这里
https://github.com/felangel/bloc/issues/1472