Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throttle function execution in dart

Is there a way in Dart to throttle function execution like this

Observable.throttle(myFunction,2000);

like image 509
Shady Aziza Avatar asked Nov 01 '18 07:11

Shady Aziza


2 Answers

Using https://pub.dartlang.org/documentation/rxdart/latest/rx/Observable/throttle.html

So, your example in Dart 2 with RxDart is

final subject = new ReplaySubject<int>();
myCaller(Event event) {
  subject.add(event);
}
subject
  .throttle(Duration(seconds: 2))
  .listen(myHandler);
like image 69
TruongSinh Avatar answered Oct 14 '22 01:10

TruongSinh


// you can run the code in dartpad: https://dartpad.dev/
typedef VoidCallback = dynamic Function();

class Throttler {
  Throttler({this.throttleGapInMillis});

  final int throttleGapInMillis;

  int lastActionTime;

  void run(VoidCallback action) {
    if (lastActionTime == null) {
      action();
      lastActionTime = DateTime.now().millisecondsSinceEpoch;
    } else {
      if (DateTime.now().millisecondsSinceEpoch - lastActionTime > (throttleGapInMillis ?? 500)) {
        action();
        lastActionTime = DateTime.now().millisecondsSinceEpoch;
      }
    }
  }
}

void main() {
  var throttler = Throttler();
  // var throttler = Throttler(throttleGapInMillis: 1000);
  throttler.run(() {
    print("will print");
  });
  throttler.run(() {
    print("will not print");
  });
  Future.delayed(Duration(milliseconds: 500), () {
    throttler.run(() {
      print("will print with delay");
    });
  });
}
like image 27
聂超群 Avatar answered Oct 14 '22 03:10

聂超群