正如 Riverpod 文档中所述,Riverpod 提供程序可以监视其他提供程序来创建“处理管道”。
我有这样的事情:
final prov = Provider<String>((ref){
final w1 = ref.watch(prov1);
final w2 = ref.watch(prov2);
final w3 = ref.watch(prov3);
final w4 = ref.watch(prov4);
final complex = expensiveFunction(w1,w2,w3,w4);
return complex;
});
Run Code Online (Sandbox Code Playgroud)
prov1可以prov4通过 UI 的各个部分单独修改,但某些 UI 操作会导致其中部分或全部快速连续更改。
我怎样才能消除呼叫expensiveFunction()直到w1..w4在 2 秒内都没有改变?
Val*_*nal 11
根据Riverpod 包作者的推文,您可以执行以下操作:
/// An extension on [Ref] with helpful methods to add a debounce.
extension RefDebounceExtension on Ref {
/// Delays an execution by a bit such that if a dependency changes multiple
/// time rapidly, the rest of the code is only run once.
Future<void> debounce(Duration duration) {
final completer = Completer<void>();
final timer = Timer(duration, () {
if (!completer.isCompleted) completer.complete();
});
onDispose(() {
timer.cancel();
if (!completer.isCompleted) {
completer.completeError(StateError('Cancelled'));
}
});
return completer.future;
}
}
final prov = FutureProvider<String>((ref) async {
final w1 = ref.watch(prov1);
final w2 = ref.watch(prov2);
final w3 = ref.watch(prov3);
final w4 = ref.watch(prov4);
await debounce(Duration(seconds: 2));
final complex = expensiveFunction(w1,w2,w3,w4);
return complex;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1404 次 |
| 最近记录: |