Skip to content

Instantly share code, notes, and snippets.

@pingbird
Last active January 26, 2022 00:58
Show Gist options
  • Save pingbird/d54b3ef98a3b450ce71472fb4f898945 to your computer and use it in GitHub Desktop.
Save pingbird/d54b3ef98a3b450ce71472fb4f898945 to your computer and use it in GitHub Desktop.
import 'dart:async';
extension<T> on Stream<T> {
Stream<T> regulate(Duration rateLimit) {
final controller = StreamController<T>();
Timer? timer;
DateTime? lastTime;
T? lastMessage;
listen(
(message) {
lastMessage = message;
final now = DateTime.now();
if (lastTime == null || (!now.isBefore(lastTime!.add(rateLimit)) && timer != null)) {
// This is either the first message or we are past the rate limit
lastTime = now;
controller.add(message);
} else {
// Schedule timer to the next event
timer ??= Timer(
lastTime!.add(rateLimit).difference(now),
() {
controller.add(lastMessage as T);
lastTime = now;
timer = null;
},
);
}
},
onError: controller.addError,
onDone: controller.close,
);
return controller.stream;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment