简体   繁体   English

Flutterriverpod debounce多个依赖提供者

[英]Flutter riverpod debounce multiple dependent providers

As described in the Riverpod docs, a Riverpod provider can watch other providers to make a "processing pipeline".如 Riverpod 文档中所述,Riverpod 提供者可以监视其他提供者来制作“处理管道”。

I have something like this:我有这样的事情:

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

prov1 to prov4 can be modified individually by various bits of UI But some UI actions cause some or all of them to change in quick succession. prov1prov4可以通过 UI 的各个位单独修改,但是某些 UI 操作会导致它们中的部分或全部快速连续更改。

How can I debounce calls to expensiveFunction() until none of w1 .. w4 have changed for say 2 secs?w1 .. w4都没有改变 2 秒之前,我怎样才能消除对expensiveFunction()的调用?

From this tweet of the author of the riverpod package, here is how you can do it:从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