Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1569)

Unified Diff: lib/src/transformers/throttle.dart

Issue 1648963002: Add reactive-inspired stream transformers: Base URL: https://github.com/dart-lang/async@master
Patch Set: Restructure failes and add more tests. Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: lib/src/transformers/throttle.dart
diff --git a/lib/src/transformers/throttle.dart b/lib/src/transformers/throttle.dart
new file mode 100644
index 0000000000000000000000000000000000000000..696eb08e9eb6612215e835216452e0c371e24f8c
--- /dev/null
+++ b/lib/src/transformers/throttle.dart
@@ -0,0 +1,44 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:async";
+import "debounce.dart";
+
+/// Drops any event that happens shortly after another undropped event.
+///
+/// If an event happens within a certain [Duration] of the most recently
+/// output event, the new event is dropped.
+/// When the duration has passed after an event that wasn't dropped,
+/// the next event will be accepted.
+///
+/// This differs from [Debounce] which restarts the timer
+/// after dropped events too.
+class Throttle<S> implements StreamTransformer<S, S> {
+ final Duration _interval;
+ final Function _createStopwatch;
+
+ /// Drops events sooner than [interval] after emitted events.
+ ///
+ /// A [createStopwatch] function can be provided to introduce a non-standard
+ /// [Stopwatch] implementation, e.g., for testing.
+ /// It defaults to using [StopWatch].
+ Throttle(Duration interval, {Stopwatch createStopwatch()})
+ : _interval = interval,
+ _createStopwatch = createStopwatch;
+
+ Stream<S> bind(Stream<S> stream) async* {
+ var interval = Duration.ZERO; // Avoid dropping the first event.
+ var stopwatch =
+ (_createStopwatch == null) ? new Stopwatch() : _createStopwatch();
+ stopwatch.start() ;
+ await for (var source in stream) {
+ if (stopwatch.elapsed >= interval) {
+ yield source;
+ stopwatch.reset();
+ interval = _interval;
+ }
+ }
+ stopwatch.stop();
+ }
+}

Powered by Google App Engine
This is Rietveld 408576698