Created
May 30, 2022 04:37
-
-
Save Kurogoma4D/bbd7a0aac0e49d0011288e6b1dbaeedd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:meta/meta.dart'; | |
import 'package:riverpod/riverpod.dart'; | |
@immutable | |
class Count { | |
final int countA; | |
final int countB; | |
Count(this.countA, this.countB); | |
@override | |
int get hashCode => runtimeType.hashCode ^ countA.hashCode ^ countB.hashCode; | |
@override | |
bool operator ==(dynamic other) => | |
identical(this, other) || | |
(other is Count && | |
identical(countA, other.countA) && | |
identical(countB, other.countB)); | |
} | |
class CountVM extends StateNotifier<Count> { | |
final Ref ref; | |
CountVM(this.ref) : super(Count(0, 0)) { | |
print('${state.countA} ${state.countB}'); | |
ref.listen(count, (_, Count value) { | |
state = value; | |
}); | |
} | |
int get countA => state.countA; | |
int get countB => state.countB; | |
} | |
final count = StateProvider((_) => Count(0, 0)); | |
final countVM = StateNotifierProvider<CountVM, Count>((ref) { | |
return CountVM(ref); | |
}); | |
final watchCountA = Provider((ref) { | |
final a = ref.watch(countVM.select((value) => value.countA)); | |
print('Detected change countA from watchCountA : $a'); | |
ref.onDispose(() => print('d a')); | |
return a; | |
}); | |
final watchCountB = Provider((ref) { | |
final b = ref.watch(countVM.select((value) => value.countB)); | |
print('Detected change countB from watchCountB : $b'); | |
ref.onDispose(() => print('d b')); | |
return b; | |
}); | |
void main() async { | |
final container = ProviderContainer(); | |
container.listen<int>(watchCountA, (_, int a) { | |
print(a); | |
}); | |
container.listen<int>(watchCountB, (_, int b) { | |
print(b); | |
}); | |
final _count = container.read(count.notifier); | |
print('change a to 1'); | |
_count.update((_) => Count(1, 0)); | |
await Future.delayed(const Duration(milliseconds: 500)); | |
print('change a to 2'); | |
_count.update((_) => Count(2, 0)); | |
await Future.delayed(const Duration(milliseconds: 500)); | |
print('change b to 1'); | |
_count.update((_) => Count(2, 1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment