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);
4条答案
按热度按时间olmpazwi1#
使用https://pub.dartlang.org/documentation/rxdart/latest/rx/Observable/throttle.html
因此,您在Dart 2中使用RxDart的示例是
bxpogfeg2#
nue99wik3#
shyt4zoc4#
按照君特·佐施鲍尔的思路,你可以使用
StreamController
将函数调用转换为Stream
,为了便于举例,我们假设myFunction
有一个int
返回值和一个int
参数。注意:请注意throttleTime的额外参数。默认值为
trailing=false
和leading=true
。如果您希望将最新样本保持在节流周期内,则您更希望使用trailing: true
和leading: false
。