Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()));
  }
like image 749
Ride Sun Avatar asked Jul 16 '20 01:07

Ride Sun


People also ask

How do I cancel a Dart stream?

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.

How do you get rid of futures in darts?

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.

How does async await work in darts?

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 .


1 Answers

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

like image 159
Ride Sun Avatar answered Nov 15 '22 04:11

Ride Sun