-
-
Save emanuel-braz/1cb2db16e8422be96fe8bcd9ea17447f to your computer and use it in GitHub Desktop.
Example of stream debouncing and throttling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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