Line data Source code
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 :
7 : /// A transformer that converts a broadcast stream into a single-subscription
8 : /// stream.
9 : ///
10 : /// This buffers the broadcast stream's events, which means that it starts
11 : /// listening to a stream as soon as it's bound.
12 : ///
13 : /// This also casts the source stream's events to type `T`. If the cast fails,
14 : /// the result stream will emit a [CastError]. This behavior is deprecated, and
15 : /// should not be relied upon.
16 : class SingleSubscriptionTransformer<S, T> implements StreamTransformer<S, T> {
17 0 : const SingleSubscriptionTransformer();
18 :
19 : Stream<T> bind(Stream<S> stream) {
20 : var subscription;
21 0 : var controller = new StreamController<T>(
22 0 : sync: true, onCancel: () => subscription.cancel());
23 0 : subscription = stream.listen((value) {
24 : // TODO(nweiz): When we release a new major version, get rid of the second
25 : // type parameter and avoid this conversion.
26 : try {
27 0 : controller.add(value as T);
28 0 : } on CastError catch (error, stackTrace) {
29 0 : controller.addError(error, stackTrace);
30 : }
31 0 : }, onError: controller.addError, onDone: controller.close);
32 0 : return controller.stream;
33 : }
34 : }
|