Appearance
StreamTransformer<S, T> abstract interface
abstract interface class StreamTransformer<S, T>Transforms a Stream.
When a stream's Stream.transform method is invoked with a StreamTransformer, the stream calls the bind method on the provided transformer. The resulting stream is then returned from the Stream.transform method.
Conceptually, a transformer is simply a function from Stream to Stream that is encapsulated into a class.
It is good practice to write transformers that can be used multiple times.
All other transforming methods on Stream, such as Stream.map, Stream.where or Stream.expand can be implemented using Stream.transform. A StreamTransformer is thus very powerful but often also a bit more complicated to use.
The StreamTransformer.fromHandlers constructor allows passing separate callbacks to react to events, errors, and the end of the stream. The StreamTransformer.fromBind constructor creates a StreamTransformer whose bind method is implemented by calling the function passed to the constructor.
Implementers
Constructors
StreamTransformer() factory const
const factory StreamTransformer(
StreamSubscription<T> Function(Stream<S> stream, bool cancelOnError) onListen,
)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.
If the transformed stream is a broadcast stream, so is the stream returned by the StreamTransformer.bind method by this transformer.
If the transformed stream is listened to multiple times, the onListen callback is called again for each new Stream.listen call. This happens whether the stream is a broadcast stream or not, but the call will usually fail for non-broadcast streams.
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:
- by allocating a StreamController and to return the result of listening to its stream. It's important to forward pause, resume and cancel events (unless the transformer intentionally wants to change this behavior).
- by creating a new class that implements StreamSubscription. Note that the subscription should run callbacks in the Zone the stream was listened to (see Zone and Zone.bindCallback).
Example:
dart
/// Starts listening to [input] and duplicates all non-error events.
StreamSubscription<int> _onListen(Stream<int> input, bool cancelOnError) {
// Create the result controller.
// Using `sync` is correct here, since only async events are forwarded.
var controller = StreamController<int>(sync: true);
controller.onListen = () {
var subscription = input.listen((data) {
// Duplicate the data.
controller.add(data);
controller.add(data);
},
onError: controller.addError,
onDone: controller.close,
cancelOnError: cancelOnError);
// Controller forwards pause, resume and cancel events.
controller
..onPause = subscription.pause
..onResume = subscription.resume
..onCancel = subscription.cancel;
};
// 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);Implementation
dart
const factory StreamTransformer(
StreamSubscription<T> onListen(Stream<S> stream, bool cancelOnError),
) = _StreamSubscriptionTransformer<S, T>;StreamTransformer.fromBind() factory
Creates a StreamTransformer based on a bind callback.
The returned stream transformer uses the bind argument to implement the StreamTransformer.bind API and can be used when the transformation is available as a stream-to-stream function.
dart
final splitDecoded = StreamTransformer<List<int>, String>.fromBind(
(stream) => stream.transform(utf8.decoder).transform(LineSplitter()));Implementation
dart
factory StreamTransformer.fromBind(Stream<T> Function(Stream<S>) bind) =
_StreamBindTransformer<S, T>;StreamTransformer.fromHandlers() factory
factory StreamTransformer.fromHandlers({
(void Function(S data, EventSink<T> sink))? handleData,
(void Function(Object error, StackTrace stackTrace, EventSink<T> sink))? handleError,
(void Function(EventSink<T> sink))? handleDone,
})Creates a StreamTransformer that delegates events to the given functions.
Example use of a duplicating transformer:
dart
stringStream.transform(StreamTransformer<String, String>.fromHandlers(
handleData: (String value, EventSink<String> sink) {
sink.add(value);
sink.add(value); // Duplicate the incoming events.
}));When a transformed stream returned from a call to bind is listened to, the source stream is listened to, and a handler function is called for each event of the source stream.
The handlers are invoked with the event data and with a sink that can be used to emit events on the transformed stream.
The handleData handler is invoked for data events on the source stream. If handleData was omitted, data events are added directly to the created stream, as if calling EventSink.add on the sink with the event value. If handleData is omitted the source stream event type, S, must be a subtype of the transformed stream event type T.
The handleError handler is invoked for each error of the source stream. If handleError is omitted, errors are forwarded directly to the transformed stream, as if calling EventSink.addError with the error and stack trace.
The handleDone handler is invoked when the source stream closes, as signaled by sending a done event. The done handler takes no event value, but can still send other events before calling EventSink.close. If handleDone is omitted, a done event on the source stream closes the transformed stream.
If any handler calls EventSink.close on the provided sink, the transformed sink closes and the source stream subscription is cancelled. No further events can be added to the sink by that handler, and no further source stream events will occur.
The sink provided to the event handlers must only be used during the call to that handler. It must not be stored and used at a later time.
Transformers created this way should be stateless. They should not retain state between invocations of handlers, because the same transformer, and therefore the same handlers, may be used on multiple streams, or on streams which can be listened to more than once. To create per-stream handlers, StreamTransformer.fromBind could be used to create a new StreamTransformer.fromHandlers per stream to transform.
dart
var controller = StreamController<String>.broadcast();
controller.onListen = () {
scheduleMicrotask(() {
controller.addError("Bad");
controller.addError("Worse");
controller.addError("Worst");
});
};
var sharedState = 0;
var transformedStream = controller.stream.transform(
StreamTransformer<String>.fromHandlers(
handleError: (error, stackTrace, sink) {
sharedState++; // Increment shared error-counter.
sink.add("Error $sharedState: $error");
}));
transformedStream.listen(print);
transformedStream.listen(print); // Listen twice.
// Listening twice to the same stream makes the transformer share the same
// state. Instead of having "Error 1: Bad", "Error 2: Worse",
// "Error 3: Worst" as output (each twice for the separate subscriptions),
// this program emits:
// Error 1: Bad
// Error 2: Bad
// Error 3: Worse
// Error 4: Worse
// Error 5: Worst
// Error 6: WorstImplementation
dart
factory StreamTransformer.fromHandlers({
void handleData(S data, EventSink<T> sink)?,
void handleError(Object error, StackTrace stackTrace, EventSink<T> sink)?,
void handleDone(EventSink<T> sink)?,
}) = _StreamHandlerTransformer<S, T>;Properties
hashCode no setter inherited
int get hashCodeThe hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
dart
external int get hashCode;runtimeType no setter inherited
Type get runtimeTypeA representation of the runtime type of the object.
Inherited from Object.
Implementation
dart
external Type get runtimeType;Methods
bind()
Transforms the provided stream.
Returns a new stream with events that are computed from events of the provided stream.
The StreamTransformer interface is completely generic, so it cannot say what subclasses do. Each StreamTransformer should document clearly how it transforms the stream (on the class or variable used to access the transformer), as well as any differences from the following typical behavior:
- When the returned stream is listened to, it starts listening to the input
stream. - Subscriptions of the returned stream forward (in a reasonable time) a StreamSubscription.pause call to the subscription of the input
stream. - Similarly, canceling a subscription of the returned stream eventually (in reasonable time) cancels the subscription of the input
stream.
"Reasonable time" depends on the transformer and stream. Some transformers, like a "timeout" transformer, might make these operations depend on a duration. Others might not delay them at all, or just by a microtask.
Transformers are free to handle errors in any way. A transformer implementation may choose to propagate errors, or convert them to other events, or ignore them completely, but if errors are ignored, it should be documented explicitly.
Implementation
dart
Stream<T> bind(Stream<S> stream);cast()
StreamTransformer<RS, RT> cast<RS, RT>()Provides a StreamTransformer<RS, RT> view of this stream transformer.
The resulting transformer will check at run-time that all data events of the stream it transforms are actually instances of S, and it will check that all data events produced by this transformer are actually instances of RT.
Implementation
dart
StreamTransformer<RS, RT> cast<RS, RT>();noSuchMethod() inherited
dynamic noSuchMethod(Invocation invocation)Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time errorThis invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
dart
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.
If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);toString() inherited
String toString()A string representation of this object.
Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.
Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.
Inherited from Object.
Implementation
dart
external String toString();Operators
operator ==() inherited
The equality operator.
The default behavior for all Objects is to return true if and only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false.Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
dart
external bool operator ==(Object other);Static Methods
castFrom()
StreamTransformer<TS, TT> castFrom<SS, ST, TS, TT>(
StreamTransformer<SS, ST> source,
)Adapts source to be a StreamTransformer<TS, TT>.
This allows source to be used at the new type, but at run-time it must satisfy the requirements of both the new type and its original type.
Data events passed into the returned transformer must also be instances of SS, and data events produced by source for those events must also be instances of TT.
Implementation
dart
static StreamTransformer<TS, TT> castFrom<SS, ST, TS, TT>(
StreamTransformer<SS, ST> source,
) {
return CastStreamTransformer<SS, ST, TS, TT>(source);
}