riverpod-retry

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Riverpod — 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)。ErrorProviderException不会触发重试:Error表示存在代码bug;ProviderException意味着依赖的provider失败,因此当前依赖的provider不会重试(底层的依赖provider会重试)。

Custom retry function

自定义重试函数

A retry function has signature
Duration? Function(int retryCount, Object error)
. Return a Duration for the delay before the next retry, or null to stop.
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? Function(int retryCount, Object error)
。返回Duration表示下次重试前的延迟时间,返回null则停止重试。
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
    retry: myRetry
    when defining the provider (or
    @Riverpod(retry: myRetry)
    with codegen).
  • Globally: Pass
    retry: myRetry
    to ProviderScope or ProviderContainer.
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)
    )。
  • 全局配置:在ProviderScopeProviderContainer中传入
    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)
(or equivalent) keeps waiting until either all retries are exhausted or the provider succeeds. So
await ref.watch(myProvider.future)
skips intermediate failures and completes when the provider finally succeeds or gives up.
ref.watch(myProvider.future)
(或等价方法)会一直等待,直到所有重试耗尽或provider执行成功。因此
await ref.watch(myProvider.future)
会跳过中间的失败,直到provider最终成功或放弃重试时才完成。