繁体   English   中英

Flutterriverpod debounce多个依赖提供者

[英]Flutter riverpod debounce multiple dependent providers

如 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;
});

prov1prov4可以通过 UI 的各个位单独修改,但是某些 UI 操作会导致它们中的部分或全部快速连续更改。

w1 .. w4都没有改变 2 秒之前,我怎样才能消除对expensiveFunction()的调用?

从riverpod package的作者的 这条推文中,您可以这样做:

/// 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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM