Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dispose subscription?

How can I dispose subscription if my class is not in StatefulWidge? Is there any method?

class EventNotifier extends ValueNotifier<List<String>> {
  EventNotifier(List<String> value) : super(value);
  final List<String> events = ['add', 'delete', 'edit'];
  final stream = Stream.periodic(const Duration(seconds: 5));
  late final streamSub = stream.listen(
    (event) {
      value.add(
        events[Random().nextInt(3)],
      );
      notifyListeners();
    },
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t believe it’s necessary in this case, since both the stream and subscription will be freed by the GC when the instance is freed.

However, ValueNotifier does have a dispose method. You can override it, and cancel your stream from there if you need to:

class EventNotifier extends ValueNotifier<List<String>> {
  // Omitted

  @override
  void dispose() {
    streamSub.cancel();
    super.dispose();
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading