How can I cancel a 'await for' in a flutter / dart bloc

Viewed 2276

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()));
  }
1 Answers
Related