userName
userName

Reputation: 945

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();
    },
  );
}

Upvotes: 0

Views: 367

Answers (1)

Michael Horn
Michael Horn

Reputation: 4089

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

Upvotes: 1

Related Questions