riverpod-cancel
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRiverpod — Cancelling and debouncing requests
Riverpod — 取消与防抖请求
Instructions
操作说明
Use ref.onDispose together with auto-dispose (or ref.watch) to cancel in-flight requests when the user leaves the page, or to debounce rapid refreshes.
结合ref.onDispose与auto-dispose(或ref.watch),在用户离开页面时取消正在进行的请求,或对频繁刷新进行防抖处理。
Cancelling when leaving the page
离开页面时取消请求
Ensure the provider is auto-dispose. When the user navigates away, the provider loses its listeners and is disposed; ref.onDispose runs. In that callback, cancel the request (e.g. close the HTTP client used for the request).
Example pattern: create an in the provider, pass it to your fetch logic, and call ref.onDispose(client.close). When the provider is disposed, the client closes and the request is cancelled. Exact API depends on your HTTP package.
http.Client()确保提供者(provider)为auto-dispose类型。当用户导航离开页面时,提供者会失去监听器并被销毁;此时ref.onDispose会执行。在该回调中,取消请求(例如关闭用于请求的HTTP客户端)。
示例模式:在提供者中创建,将其传入你的获取逻辑,并调用ref.onDispose(client.close)。当提供者被销毁时,客户端会关闭,请求随之取消。具体API取决于你使用的HTTP包。
http.Client()Debouncing refreshes
防抖刷新
If the user triggers refresh multiple times quickly, you can delay the actual request until they stop (e.g. 500ms). Pattern:
- In the provider, set a flag (e.g. ) and ref.onDispose(() => didDispose = true).
didDispose = false - await Future.delayed(duration).
- If didDispose is true, the user triggered another refresh during the delay; throw to abort (Riverpod catches and ignores). Otherwise create the client, register onDispose(client.close), and run the request.
So: delay first, then create client and run request; disposal during the delay aborts, disposal after creates client cancels the request.
如果用户快速多次触发刷新,你可以延迟实际请求直到他们停止操作(例如延迟500毫秒)。实现模式:
- 在提供者中设置一个标记(例如),并通过**ref.onDispose(() => didDispose = true)**来更新标记。
didDispose = false - await Future.delayed(duration)。
- 如果didDispose为true,说明用户在延迟期间触发了另一次刷新;此时抛出异常以中止请求(Riverpod会捕获并忽略该异常)。否则创建客户端,注册onDispose(client.close),并执行请求。
即:先延迟,再创建客户端并执行请求;延迟期间销毁提供者则中止请求,创建客户端后销毁则取消请求。
Reusable extension
可复用扩展
You can implement an extension on Ref that returns a debounced/cancellable client:
- Use onDispose to set a "cancelled" flag.
- Wait for the debounce duration; if disposed, throw.
- Create the client, onDispose(client.close), return the client.
Use this extension in your activity/provider so all call sites get debounce + cancel behavior. See the official Riverpod "cancel" how-to for a full extension example.
你可以为Ref实现一个扩展,返回一个支持防抖和取消的客户端:
- 使用onDispose设置“已取消”标记。
- 等待防抖时长;如果已销毁,则抛出异常。
- 创建客户端,调用onDispose(client.close),返回该客户端。
在你的页面/提供者中使用此扩展,这样所有调用位置都能获得防抖+取消的行为。完整的扩展示例可参考Riverpod官方的“取消操作”指南。