Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2013, 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 library barback.stream_replayer; | |
| 6 | |
| 7 import 'dart:async'; | |
| 8 import 'dart:collection'; | |
| 9 | |
| 10 import 'utils.dart'; | |
| 11 | |
| 12 /// Records the values and errors that are sent through a stream and allows them | |
| 13 /// to be replayed arbitrarily many times. | |
| 14 class StreamReplayer<T> { | |
| 15 /// The wrapped stream. | |
| 16 final Stream<T> _stream; | |
| 17 | |
| 18 /// Whether or not [_stream] has been closed. | |
| 19 bool _isClosed = false; | |
| 20 | |
| 21 /// The buffer of events or errors that have already been emitted by | |
| 22 /// [_stream]. | |
| 23 /// | |
| 24 /// Each element is a [Either] that's either a value or an error sent through | |
| 25 /// the stream. | |
| 26 final _buffer = new Queue<Either<T, dynamic>>(); | |
| 27 | |
| 28 /// The controllers that are listening for future events from [_stream]. | |
| 29 final _controllers = new Set<StreamController<T>>(); | |
| 30 | |
| 31 StreamReplayer(this._stream) { | |
| 32 _stream.listen((data) { | |
| 33 _buffer.add(new Either<T, dynamic>.withFirst(data)); | |
| 34 for (var controller in _controllers) { | |
| 35 controller.add(data); | |
| 36 } | |
| 37 }, onError: (error) { | |
| 38 _buffer.add(new Either<T, dynamic>.withSecond(error)); | |
| 39 for (var controller in _controllers) { | |
| 40 controller.addError(error); | |
| 41 } | |
| 42 }, onDone: () { | |
| 43 _isClosed = true; | |
| 44 for (var controller in _controllers) { | |
| 45 controller.close(); | |
| 46 } | |
| 47 _controllers.clear(); | |
| 48 }); | |
| 49 } | |
| 50 | |
| 51 /// Returns a stream that replays the values and errors of the input stream. | |
| 52 /// | |
| 53 /// This stream is a buffered stream regardless of whether the input stream | |
| 54 /// was broadcast or buffered. | |
| 55 Stream<T> getReplay() { | |
| 56 var controller = new StreamController<T>(); | |
| 57 for (var eventOrError in _buffer) { | |
| 58 eventOrError.match(controller.add, controller.addError); | |
|
Bob Nystrom
2013/08/27 17:59:57
Oh, that cleaned up nicely.
| |
| 59 } | |
| 60 if (_isClosed) { | |
| 61 controller.close(); | |
| 62 } else { | |
| 63 _controllers.add(controller); | |
| 64 } | |
| 65 return controller.stream; | |
| 66 } | |
| 67 } | |
| OLD | NEW |