Skip to content

Instantly share code, notes, and snippets.

@zjor
Created March 2, 2020 12:47
Show Gist options
  • Save zjor/c9a1a64fd22e802c8844a272168e9bce to your computer and use it in GitHub Desktop.
Save zjor/c9a1a64fd22e802c8844a272168e9bce to your computer and use it in GitHub Desktop.
Example of stream debouncing and throttling
import 'dart:async';
import 'dart:math';
import 'package:stream_transform/stream_transform.dart';
StreamController<int> controller = StreamController<int>.broadcast();
void probe(int id, int delay) {
print("Submitted(ID: $id; delay: $delay)");
controller.add(id);
}
void invokeWithDelays(List<List<int>> delays) async {
for (List<int> delay in delays) {
await Future.delayed(
Duration(milliseconds: delay[1]), () => probe(delay[0], delay[1]));
}
}
void main(List<String> args) async {
Random random = Random(0);
final StreamTransformer<int, dynamic> debounce = StreamTransformer.fromBind(
(s) => s.debounce(const Duration(milliseconds: 100)));
final StreamTransformer<int, dynamic> debounceBuffer = StreamTransformer.fromBind(
(s) => s.debounceBuffer(const Duration(milliseconds: 100)));
final StreamTransformer<int, dynamic> throttle = StreamTransformer.fromBind(
(s) => s.throttle(const Duration(milliseconds: 100)));
controller.stream
.transform(debounceBuffer)
.listen((event) => print("debounceBuffer: $event"));
controller.stream
.transform(debounce)
.listen((event) => print("debounce: $event"));
controller.stream
.transform(throttle)
.listen((event) => print("throttle: $event"));
final List<List<int>> delays = [];
List<int>.generate(10, (i) => i + 1).forEach((id) {
delays.add([id, 50 + random.nextInt(200)]);
});
await invokeWithDelays(delays);
await controller.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment