-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Description
Currently, mutations don't have a keep-alive option. If a mutation is global and shared across multiple pages, it will be killed if the page no longer listens to the mutation. I understand this will require manual resetting of the mutation's state. For example, I need to manage a global mutation in my app that sends a verification code. When the verification code countdown ends and the verification code can be sent again, I reset the mutation's state to allow sending verification codes.
Mutation is very helpful in simplifying the code, but the only thing that prevents me from using mutation is that mutation cannot survive when there is no listener. Maybe there is something wrong with the way I designed the code or I didn’t pay attention to the correct way to use mutation.
Here is how my service is implemented:
final sendSmsCodeStateProvider = NotifierProvider(() => SendSmsCodeStateNotifier());
class SendSmsCodeStateNotifier extends Notifier<Spec<void>> {
@override
Spec<void> build() {
return Spec.initial();
}
Future<void> sendSmsCode(String phoneNumber) async {
state = Spec.loading();
final smsAuthService = ref.read(smsAuthServiceProvider);
final sendSmsCodeCountdownNotifier = ref.read(sendSmsCodeCountdownProvider.notifier);
await smsAuthService.sendSmsCode(phoneNumber);
sendSmsCodeCountdownNotifier.startCountdown();
state = Spec.success(null);
}
Future<void> reset() async {
state = Spec.initial();
}
}final sendSmsCodeCountdownProvider = NotifierProvider(() => SendSmsCodeCountdownNotifier());
class SendSmsCodeCountdownNotifier extends Notifier<int> {
Timer? timer;
@override
int build() {
return 0;
}
void startCountdown() {
state = 60;
timer?.cancel();
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
state = state - 1;
if (state == 0) {
final sendSmsCodeStateNotifier = ref.read(sendSmsCodeStateProvider.notifier);
sendSmsCodeStateNotifier.reset();
timer?.cancel();
}
});
}
}