写入流程保持显式。
把更新定义为提供者方法,用 MutationToken 监控状态,并通过 ref.invoke(call) 执行。
更新构件
mutation 是 mutate(token, body, concurrency: ...) 返回的 Call<R, State>。
Token
late final renameMut = mutation<void>(#rename)
Execution
await ref.invoke(provider.rename(...))
State
通过 ref.watch(token) 读取空闲 / 进行中 / 成功 / 错误
提示
与 notifier.method() 风格的接口不同,miniriverpod 把更新执行当作一等公民的调用对象。
执行更新
使用 ref.invoke,让取消与丢弃行为都能显式反馈给调用方。
运行
并发选项
concurrent : run all calls in parallel (default).
queue : FIFO; keep running queued calls even after an error.
restart : cancel previous run, keep only latest call.
dropLatest : drop incoming calls while one is running.
示例:乐观更新 + restart
常见的写入模式是先乐观更新 AsyncData,再与服务端响应同步。
class UserProvider extends AsyncProvider<User?> {
UserProvider() : super.args(null);
late final renameMut = mutation<void>(#rename);
Call<void, AsyncValue<User?>> rename(String newName) => mutate(
renameMut,
(ref) async {
final cur = ref.watch(this).valueOrNull;
ref.state = AsyncData((cur ?? const User()).copyWith(name: newName), isRefreshing: true);
final api = ref.watch(apiProvider);
await api.rename(newName);
ref.state = AsyncData(await api.me());
},
concurrency: Concurrency.restart,
);
}
restart 可能会向旧调用者抛出 CancelledMutation。
dropLatest 在忙碌时可能抛出 DroppedMutation。
如果想抑制短暂的取消错误,可以在 UI 中捕获这些异常。