riverpod-retry
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRiverpod — Automatic retry
Riverpod — 自动重试
Instructions
说明
Riverpod retries providers when their computation throws. Retry can be customized per provider or globally.
当provider的计算抛出异常时,Riverpod会重试该provider。重试机制可针对单个provider或全局进行自定义。
Default behavior
默认行为
By default a provider is retried up to a limit (e.g. 10 times) with exponential backoff (e.g. 200ms to 6.4s). Error and ProviderException are not retried: Error indicates a bug; ProviderException means a dependency failed, so the dependent provider is not retried (the underlying one is).
默认情况下,provider最多会重试指定次数(例如10次),并采用指数退避策略(例如延迟从200ms递增至6.4s)。Error和ProviderException不会触发重试:Error表示存在代码bug;ProviderException意味着依赖的provider失败,因此当前依赖的provider不会重试(底层的依赖provider会重试)。
Custom retry function
自定义重试函数
A retry function has signature . Return a Duration for the delay before the next retry, or null to stop.
Duration? Function(int retryCount, Object error)dart
Duration? myRetry(int retryCount, Object error) {
if (retryCount >= 5) return null;
if (error is ProviderException) return null;
return Duration(milliseconds: 200 * (1 << retryCount));
}重试函数的签名为 。返回Duration表示下次重试前的延迟时间,返回null则停止重试。
Duration? Function(int retryCount, Object error)dart
Duration? myRetry(int retryCount, Object error) {
if (retryCount >= 5) return null;
if (error is ProviderException) return null;
return Duration(milliseconds: 200 * (1 << retryCount));
}Where to set it
配置位置
- Per provider: Pass when defining the provider (or
retry: myRetrywith codegen).@Riverpod(retry: myRetry) - Globally: Pass to ProviderScope or ProviderContainer.
retry: myRetry
dart
// Global
ProviderScope(retry: myRetry, child: MyApp())
// Per provider (manual)
final myProvider = Provider<int>(retry: myRetry, (ref) => 0);- 单个provider:定义provider时传入(使用代码生成时则为
retry: myRetry)。@Riverpod(retry: myRetry) - 全局配置:在ProviderScope或ProviderContainer中传入。
retry: myRetry
dart
// 全局配置
ProviderScope(retry: myRetry, child: MyApp())
// 单个provider(手动定义)
final myProvider = Provider<int>(retry: myRetry, (ref) => 0);Disabling retry
禁用重试
Return null always:
dart
ProviderScope(retry: (retryCount, error) => null, child: MyApp())始终返回null即可:
dart
ProviderScope(retry: (retryCount, error) => null, child: MyApp())Awaiting async providers with retry
等待带重试的异步provider
ref.watch(myProvider.future)await ref.watch(myProvider.future)ref.watch(myProvider.future)await ref.watch(myProvider.future)