Chromium Code Reviews| OLD | NEW |
|---|---|
| (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 "throttle.dart"; | |
|
nweiz
2016/03/01 02:10:04
Nit: newline between these two imports.
Lasse Reichstein Nielsen
2016/03/01 16:51:17
Acknowledged.
| |
| 7 | |
| 8 /// Drops any event that happens shortly after another event. | |
| 9 /// | |
| 10 /// If an event happens within a certain [Duration] of the previous event, | |
| 11 /// the new event is dropped from the result stream. | |
| 12 /// The dropped event will still cause following events to be dropped | |
|
nweiz
2016/03/01 02:10:04
Nit: "will still cause" -> "still causes"
Lasse Reichstein Nielsen
2016/03/01 16:51:17
Acknowledged.
| |
| 13 /// until the entire duration has passed without any events. | |
| 14 /// | |
| 15 /// This differs from [Throttle] which only restarts its timer at events | |
| 16 /// that aren't dropped. | |
| 17 /// | |
| 18 /// Any error in the source stream will be forwarded to the transformed stream | |
| 19 /// and will terminate the transformation. | |
| 20 class Debounce<S> implements StreamTransformer<S, S> { | |
| 21 final Duration _interval; | |
| 22 final Function _createStopwatch; | |
| 23 | |
| 24 /// Drops events sooner than [interval] after any other event. | |
| 25 /// | |
| 26 /// A [createStopwatch] function can be provided to introduce a non-standard | |
| 27 /// [Stopwatch] implementation, e.g., for testing | |
|
nweiz
2016/03/01 02:10:03
Nit: "testing" -> "testing."
Lasse Reichstein Nielsen
2016/03/01 16:51:16
Acknowledged.
| |
| 28 /// It defaults to using [StopWatch]. | |
|
nweiz
2016/03/01 02:10:04
Nit: "StopWatch" -> "Stopwatch"
Lasse Reichstein Nielsen
2016/03/01 16:51:16
Acknowledged.
| |
| 29 Debounce(Duration interval, {Stopwatch createStopwatch()}) | |
|
nweiz
2016/03/01 02:10:04
Up to you, but I'd just use the clock package here
Lasse Reichstein Nielsen
2016/03/01 16:51:17
I don't really like introducing an abstraction lay
| |
| 30 : _interval = interval, | |
| 31 _createStopwatch = createStopwatch; | |
| 32 | |
| 33 Stream<S> bind(Stream<S> stream) async* { | |
| 34 var interval = Duration.ZERO; // Avoid dropping the first event. | |
| 35 var stopwatch = | |
| 36 (_createStopwatch == null) ? new Stopwatch() : _createStopwatch(); | |
| 37 stopwatch.start() ; | |
| 38 await for (var source in stream) { | |
| 39 if (stopwatch.elapsed >= interval) { | |
| 40 yield source; | |
| 41 interval = _interval; | |
| 42 } | |
| 43 stopwatch.reset(); | |
| 44 } | |
| 45 stopwatch.stop(); | |
| 46 } | |
| 47 } | |
| OLD | NEW |