A source of asynchronous data events.
A Stream provides a way to receive a sequence of events.Each event is either a data event, also called anelement of the stream,or an error event, which is a notification that something has failed.When a stream has emitted all its events,a single "done" event notifies the listener that the end has been reached.
You produce a stream by calling anasync* function, which then returnsa stream. Consuming that stream will lead the function to emit eventsuntil it ends, and the stream closes.You consume a stream either using anawait for loop, which is availableinside anasync orasync* function, or by forwarding its events directlyusingyield* inside anasync* function.Example:
Stream<T> optionalMap<T>( Stream<T> source , [T Function(T)? convert]) async* { if (convert == null) { yield* source; } else { await for (var event in source) { yield convert(event); } }}When this function is called, it immediately returns aStream<T> object.Then nothing further happens until someone tries to consume that stream.At that point, the body of theasync* function starts running.If theconvert function was omitted, theyield* will listen to thesource stream and forward all events, date and errors, to the returnedstream. When thesource stream closes, theyield* is done,and theoptionalMap function body ends too. This closes the returnedstream.If aconvertis supplied, the function instead listens on the sourcestream and enters anawait for loop whichrepeatedly waits for the next data event.On a data event, it callsconvert with the value and emits the resulton the returned stream.If no error events are emitted by thesource stream,the loop ends when thesource stream does,then theoptionalMap function body completes,which closes the returned stream.On an error event from thesource stream,theawait for re-throws that error, which breaks the loop.The error then reaches the end of theoptionalMap function body,since it's not caught.That makes the error be emitted on the returned stream, which then closes.
TheStream class also provides functionality which allows you tomanually listen for events from a stream, or to convert a streaminto another stream or into a future.
TheforEach function corresponds to theawait for loop,just asIterable.forEach corresponds to a normalfor/in loop.Like the loop, it will call a function for each data event and break on anerror.
The more low-levellisten method is what every other method is based on.You calllisten on a stream to tell it that you want to receiveevents, and to register the callbacks which will receive those events.When you calllisten, you receive aStreamSubscription objectwhich is the active object providing the events,and which can be used to stop listening again,or to temporarily pause events from the subscription.
There are two kinds of streams: "Single-subscription" streams and"broadcast" streams.
A single-subscription stream allows only a single listener during the wholelifetime of the stream.It doesn't start generating events until it has a listener,and it stops sending events when the listener is unsubscribed,even if the source of events could still provide more.The stream created by anasync* function is a single-subscription stream,but each call to the function creates a new such stream.
Listening twice on a single-subscription stream is not allowed, even afterthe first subscription has been canceled.
Single-subscription streams are generally used for streaming chunks oflarger contiguous data, like file I/O.
A broadcast stream allows any number of listeners, and it firesits events when they are ready, whether there are listeners or not.
Broadcast streams are used for independent events/observers.
If several listeners want to listen to a single-subscription stream,useasBroadcastStream to create a broadcast stream on top of thenon-broadcast stream.
On either kind of stream, stream transformations, such aswhere andskip, return the same type of stream as the one the method was called on,unless otherwise noted.
When an event is fired, the listener(s) at that time will receive the event.If a listener is added to a broadcast stream while an event is being fired,that listener will not receive the event currently being fired.If a listener is canceled, it immediately stops receiving events.Listening on a broadcast stream can be treated as listening on a new streamcontaining only the events that have not yet been emitted when thelistencall occurs.For example thefirst getter listens to the stream, then returns the firstevent that listener receives.This is not necessarily the first even emitted by the stream, but the firstof theremaining events of the broadcast stream.
When the "done" event is fired, subscribers are unsubscribed beforereceiving the event. After the event has been sent, the stream has nosubscribers. Adding new subscribers to a broadcast stream after this pointis allowed, but they will just receive a new "done" event as soonas possible.
Stream subscriptions always respect "pause" requests. If necessary they needto buffer their input, but often, and preferably they can simply requesttheir input to pause too.
The default implementation ofisBroadcast returns false.A broadcast stream inheriting fromStream must overrideisBroadcastto returntrue if it wants to signal that it behaves like a broadcaststream.
Constructors
- Stream()
- const
- Stream.empty({@Since.new("3.2")boolbroadcast})
- Creates an empty broadcast stream.constfactory
- Stream.error(Objecterror, [StackTrace?stackTrace])
- Creates a stream which emits a single error event before completing.factory
- Stream.eventTransformed(Streamsource,EventSinkmapSink(EventSink<
T> sink)) - Creates a stream where all events of an existing stream are piped througha sink-transformation.factory
- Stream.fromFuture(Future<
T> future) - Creates a new single-subscription stream from the future.factory
- Stream.fromFutures(Iterable<
Future< futures)T> > - Create a single-subscription stream from a group of futures.factory
- Stream.fromIterable(Iterable<
T> elements) - Creates a stream that gets its data from
elements.factory - Stream.multi(voidonListen(MultiStreamController<
T> ), {boolisBroadcast =false}) - Creates a multi-subscription stream.factory
- Stream.periodic(Durationperiod, [Tcomputation(intcomputationCount)?])
- Creates a stream that repeatedly emits events at
periodintervals.factory - Stream.value(Tvalue)
- Creates a stream which emits a single data event before closing.factory
Properties
- first→Future<
T> - The first element of this stream.no setter
- hashCode→int
- The hash code for this object.no setterinherited
- isBroadcast→bool
- Whether this stream is a broadcast stream.no setter
- isEmpty→Future<
bool> - Whether this stream contains any elements.no setter
- last→Future<
T> - The last element of this stream.no setter
- length→Future<
int> - The number of elements in this stream.no setter
- runtimeType→Type
- A representation of the runtime type of the object.no setterinherited
- single→Future<
T> - The single element of this stream.no setter
Methods
- any(
booltest(Telement))→Future< bool> - Checks whether
testaccepts any element provided by this stream. - asBroadcastStream(
{voidonListen(StreamSubscription< T> subscription)?,voidonCancel(StreamSubscription<T> subscription)?})→Stream<T> - Returns a multi-subscription stream that produces the same events as this.
- asyncExpand<
E> (Stream< E> ?convert(Tevent))→Stream<E> - Transforms each element into a sequence of asynchronous events.
- asyncMap<
E> (FutureOr< E> convert(Tevent))→Stream<E> - Creates a new stream with each data event of this stream asynchronouslymapped to a new event.
- cast<
R> ()→Stream< R> - Adapt this stream to be a
Stream<R>. - contains(
Object?needle)→Future< bool> - Returns whether
needleoccurs in the elements provided by this stream. - distinct(
[boolequals(Tprevious,Tnext)?])→Stream< T> - Skips data events if they are equal to the previous data event.
- drain<
E> ([E?futureValue])→Future< E> - Discards all data on this stream, but signals when it is done or an erroroccurred.
- elementAt(
intindex)→Future< T> - Returns the value of the
indexth data event of this stream. - every(
booltest(Telement))→Future< bool> - Checks whether
testaccepts all elements provided by this stream. - expand<
S> (Iterable< S> convert(Telement))→Stream<S> - Transforms each element of this stream into a sequence of elements.
- firstWhere(
booltest(Telement), {TorElse()?})→Future< T> - Finds the first element of this stream matching
test. - fold<
S> (SinitialValue,Scombine(Sprevious,Telement))→Future< S> - Combines a sequence of values by repeatedly applying
combine. - forEach(
voidaction(Telement))→Future< void> - Executes
actionon each element of this stream. - handleError(
FunctiononError, {booltest(dynamicerror)?})→Stream< T> - Creates a wrapper Stream that intercepts some errors from this stream.
- join(
[Stringseparator =""])→Future< String> - Combines the string representation of elements into a single string.
- lastWhere(
booltest(Telement), {TorElse()?})→Future< T> - Finds the last element in this stream matching
test. - listen(
voidonData(Tevent)?, {Function?onError,voidonDone()?,bool?cancelOnError})→StreamSubscription< T> - Adds a subscription to this stream.
- map<
S> (Sconvert(Tevent))→Stream< S> - Transforms each element of this stream into a new stream event.
- noSuchMethod(
Invocationinvocation)→ dynamic - Invoked when a nonexistent method or property is accessed.inherited
- pipe(
StreamConsumer< T> streamConsumer)→Future - Pipes the events of this stream into
streamConsumer. - reduce(
Tcombine(Tprevious,Telement))→Future< T> - Combines a sequence of values by repeatedly applying
combine. - singleWhere(
booltest(Telement), {TorElse()?})→Future< T> - Finds the single element in this stream matching
test. - skip(
intcount)→Stream< T> - Skips the first
countdata events from this stream. - skipWhile(
booltest(Telement))→Stream< T> - Skip data events from this stream while they are matched by
test. - take(
intcount)→Stream< T> - Provides at most the first
countdata events of this stream. - takeWhile(
booltest(Telement))→Stream< T> - Forwards data events while
testis successful. - timeout(
DurationtimeLimit, {voidonTimeout(EventSink< T> sink)?})→Stream<T> - Creates a new stream with the same events as this stream.
- toList(
)→Future< List< T> > - Collects all elements of this stream in aList.
- toSet(
)→Future< Set< T> > - Collects the data of this stream in aSet.
- toString(
)→String - A string representation of this object.inherited
- transform<
S> (StreamTransformer< T,S> streamTransformer)→Stream<S> - Applies
streamTransformerto this stream. - where(
booltest(Tevent))→Stream< T> - Creates a new stream from this stream that discards some elements.
Operators
- operator ==(
Objectother)→bool - The equality operator.inherited