Search code examples
dartdart-async

Cancel StreamSubscription from Inside its Callback


Here is a (simplified) scenario of the situation:

stream.listen((bool result) {
  if (result) {
    // should cancel the subscription
  }
});

I want to stop listening to a Stream based on its content, but I cannot wrap my head about it enough to come to a conclusion.

StreamSubscription streamSubscription = stream.listen((_) {});

streamSubscription.cancel(); // cancels the subscription

With cancel() I can normally cancel my subscription, but I cannot access streamSubscription in the listen callback.


Solution

  • You need to split variable declaration and initialization:

    StreamSubscription streamSubscription;
    streamSubscription = stream.listen((bool result) {
      if (result) {
        streamSubscription.cancel();
      }
    });