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

Side by Side 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 unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 import "dart:async";
6 import "debounce.dart";
7
8 /// Drops any event that happens shortly after another undropped event.
9 ///
10 /// If an event happens within a certain [Duration] of the most recently
11 /// output event, the new event is dropped.
12 /// When the duration has passed after an event that wasn't dropped,
13 /// the next event will be accepted.
14 ///
15 /// This differs from [Debounce] which restarts the timer
16 /// after dropped events too.
17 class Throttle<S> implements StreamTransformer<S, S> {
18 final Duration _interval;
19 final Function _createStopwatch;
20
21 /// Drops events sooner than [interval] after emitted events.
22 ///
23 /// A [createStopwatch] function can be provided to introduce a non-standard
24 /// [Stopwatch] implementation, e.g., for testing.
25 /// It defaults to using [StopWatch].
26 Throttle(Duration interval, {Stopwatch createStopwatch()})
27 : _interval = interval,
28 _createStopwatch = createStopwatch;
29
30 Stream<S> bind(Stream<S> stream) async* {
31 var interval = Duration.ZERO; // Avoid dropping the first event.
32 var stopwatch =
33 (_createStopwatch == null) ? new Stopwatch() : _createStopwatch();
34 stopwatch.start() ;
35 await for (var source in stream) {
36 if (stopwatch.elapsed >= interval) {
37 yield source;
38 stopwatch.reset();
39 interval = _interval;
40 }
41 }
42 stopwatch.stop();
43 }
44 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698