Closed kaboc closed 1 year ago
I'm not sure if it is intentional, but what is possible with Stream
(as follows) is impossible with StateNotifier
's addListener()
, which seems inconvenient and confusing for me.
StreamSubscription _counterSubscription;
Timer _timer;
void main() {
final counter = Counter();
_counterSubscription = counter.stream.listen(_counterListener);
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
counter.increment();
});
}
void _counterListener(int state) {
print('Counter: $state');
if (state == 3) {
_counterSubscription.cancel();
_timer.cancel();
}
}
Output:
Counter: 1
Counter: 2
Counter: 3
It's intentional But we can do something about it.
I made a PR on Flutter about optimizing ValueNotifier, which supports this use-case. We could do the same thing here too
Still an issue to this day, can we do something about it?
No, I don't plan on changing it as this point.
It causes an exception to remove a listener inside itself using the function returned from
addListener()
ofStateNotifier
.To Reproduce
Run the code below and see the output.
Output:
Expected behavior
No exception occurs.