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 [TypeError]. This behavior is deprecated, and 15 : /// should not be relied upon. 16 : class SingleSubscriptionTransformer<S, T> extends StreamTransformerBase<S, T> { 17 0 : const SingleSubscriptionTransformer(); 18 : 19 0 : @override 20 : Stream<T> bind(Stream<S> stream) { 21 : late StreamSubscription<S> subscription; 22 : var controller = 23 0 : StreamController<T>(sync: true, onCancel: () => subscription.cancel()); 24 0 : subscription = stream.listen((value) { 25 : // TODO(nweiz): When we release a new major version, get rid of the second 26 : // type parameter and avoid this conversion. 27 : try { 28 0 : controller.add(value as T); 29 0 : } on TypeError catch (error, stackTrace) { 30 0 : controller.addError(error, stackTrace); 31 : } 32 0 : }, onError: controller.addError, onDone: controller.close); 33 0 : return controller.stream; 34 : } 35 : }