| 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();
|
| + }
|
| +}
|
|
|