Is there a way in Dart
to throttle function execution like this
Observable.throttle(myFunction,2000);
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);
// 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");
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With