I am using a stream to read out location data in a bloc. I have a start and a stop event. In the stop method, I cancel the stream subscription. When I use listen
to a stream to yield
the state the inside where the yield
statement is never gets called.
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();
}
When I replace the listen
to await for
I don't see any way
to stop this from yielding events because the subscription handle is gone.
Any ideas? Any explanations?
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()));
}
subscription. cancel(); .... }); There can be cases where you can't access the subscription object yet, but that's only possible if the stream breaks the Stream contract and starts sending events immediately when it's listened to.
What you can do to resolve your future is, add a . then() after the function call so it waits for the future and when it comes, converts it to the data type that you want.
Summary of asynchronous programming in Dart Asynchronous function is a function that returns the type of Future. We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await .
The problem is that I did not understand the behavior of yield completely. Also, the dart framework has some shortcomings.
The problem was discussed in detail with the dart makers, here.
https://github.com/dart-lang/sdk/issues/42717
and here
https://github.com/felangel/bloc/issues/1472
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With