Creates a StreamTransformer based on the given onListen
callback.
The returned stream transformer uses the provided onListen
callback when a transformed stream is listened to. At that time, the callback receives the input stream (the one passed to bind) and a boolean flag cancelOnError
to create a StreamSubscription.
The onListen
callback does not receive the handlers that were passed to Stream.listen. These are automatically set after the call to the onListen
callback (using StreamSubscription.onData, StreamSubscription.onError and StreamSubscription.onDone).
Most commonly, an onListen
callback will first call Stream.listen on the provided stream (with the corresponding cancelOnError
flag), and then return a new StreamSubscription.
There are two common ways to create a StreamSubscription:
Example:
/// Starts listening to [input] and duplicates all non-error events. StreamSubscription<int> _onListen(Stream<int> input, bool cancelOnError) { StreamSubscription<String> subscription; // Create controller that forwards pause, resume and cancel events. var controller = new StreamController<String>( onPause: () { subscription.pause(); }, onResume: () { subscription.resume(); }, onCancel: () => subscription.cancel(), sync: true); // "sync" is correct here, since events are forwarded. // Listen to the provided stream using `cancelOnError`. subscription = input.listen((data) { // Duplicate the data. controller.add(data); controller.add(data); }, onError: controller.addError, onDone: controller.close, cancelOnError: cancelOnError); // Return a new [StreamSubscription] by listening to the controller's // stream. return controller.stream.listen(null); } // Instantiate a transformer: var duplicator = const StreamTransformer<int, int>(_onListen); // Use as follows: intStream.transform(duplicator);
const factory StreamTransformer( StreamSubscription<T> onListen( Stream<S> stream, bool cancelOnError)) = _StreamSubscriptionTransformer<S, T>;
© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/2.0.0/dart-async/StreamTransformer/StreamTransformer.html