rrousselGit / state_notifier

ValueNotifier, but outside Flutter and with some extra perks
MIT License
311 stars 28 forks source link

StateNotifier invokes listener without checking value equality while ValueNotifier did #50

Closed lcdsmao closed 3 years ago

lcdsmao commented 3 years ago

Describe what scenario you think is uncovered by the existing examples/articles I noticed that StateNotifier's listener will be called when updated with the same value, which is different from ValueNotifier. Maybe it's better to clarify this in the section of Differences with ValueNotifier. ​

Describe why existing examples/articles do not cover this case Test code:

 ​test('StateNotifier change with same value', () async {
   ​final stateNotifier = StateController(0);
   ​final valueNotifier = ValueNotifier(0);

   ​var stateCount = 0;
   ​var valueCount = 0;

   ​stateNotifier.addListener((state) {
     ​stateCount++;
   ​}, fireImmediately: false);
   ​valueNotifier.addListener(() {
     ​valueCount++;
   ​});

   ​expect(stateCount, 0);
   ​expect(valueCount, 0);

   ​stateNotifier.state = 0;
   ​valueNotifier.value = 0;

   ​expect(stateCount, 1);
   ​expect(valueCount, 0);

   ​stateNotifier.state = 0;
   ​valueNotifier.value = 0;

   ​expect(stateCount, 2);
   ​expect(valueCount, 0);

   ​stateNotifier.state = 100;
   ​valueNotifier.value = 100;

   ​expect(stateCount, 3);
   ​expect(valueCount, 1);
 ​});

Additional context When using ref.listen (riverpod 1.0.0) to listening to a StateNotifierProvider for showing snackbar., I noticed this different behavior from ValueNotifier.

rrousselGit commented 3 years ago

StateNotifier was updated to filter values using identical, and this behaviour was documented.

I would expect this to be a solution for simple cases like you described (numbers/enums), without performance impact on complex objects.