有没有办法Dart
像这样限制函数执行
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");
});
});
}
import 'package:flutter/foundation.dart';
import 'dart:async';
// A simple class for throttling functions execution
class Throttler {
@visibleForTesting
final int milliseconds;
@visibleForTesting
Timer? timer;
@visibleForTesting
static const kDefaultDelay = 2000;
Throttler({this.milliseconds = kDefaultDelay});
void run(VoidCallback action) {
if (timer?.isActive ?? false) return;
timer?.cancel();
action();
timer = Timer(Duration(milliseconds: milliseconds), () {});
}
void dispose() {
timer?.cancel();
}
}
// How to use
void main() {
var throttler = Throttler();
throttler.run(() {
print("will print");
});
throttler.run(() {
print("will not print");
});
Future.delayed(const Duration(milliseconds: 2000), () {
throttler.run(() {
print("will print with delay");
});
});
throttler.dispose();
}
沿着 Günter Zöchbauer 的思路,您可以使用 aStreamController
将函数调用转换为 a Stream
。为了这个例子,假设它myFunction
有一个int
返回值和一个int
参数。
import 'package:rxdart/rxdart.dart';
// This is just a setup for the example
Stream<int> timedMyFunction(Duration interval) {
late StreamController<int> controller;
Timer? timer;
int counter = 0;
void tick(_) {
counter++;
controller.add(myFunction(counter)); // Calling myFunction here
}
void startTimer() {
timer = Timer.periodic(interval, tick);
}
void stopTimer() {
if (timer != null) {
timer?.cancel();
timer = null;
}
}
controller = StreamController<int>(
onListen: startTimer,
onPause: stopTimer,
onResume: startTimer,
onCancel: stopTimer,
);
return controller.stream;
}
// Setting up a stream firing twice a second of the values of myFunction
var rapidStream = timedMyFunction(const Duration(milliseconds: 500));
// Throttling the stream to once in every two seconds
var throttledStream = rapidStream.throttleTime(Duration(seconds: 2)).listen(myHandler);