Support for asynchronous programming, with classes such as Future and Stream.
For an introduction to using dart:async, see the dart:async section of the language tour
(https://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-asynchronous-programming). Also see articles
(https://www.dartlang.org/articles/) such as Using Future Based APIs
(https://www.dartlang.org/articles/using-future-based-apis/).
This is an experimental API.
Get the StackTrace
attached to o
.
If object o
was thrown and caught in a dart:async method, a StackTrace
object was attached to it. Use getAttachedStackTrace
to get that object.
Returns null
if no StackTrace
was attached.
Runs the given callback
asynchronously.
Callbacks registered through this function are always executed in order and are guaranteed to run before other asynchronous events (like Timer
events, or DOM events).
Warning: it is possible to starve the DOM by registering asynchronous callbacks through this method. For example the following program will run the callbacks without ever giving the Timer callback a chance to execute:
Timer.run(() { print("executed"); }); // Will never be executed; foo() { asyncRun(foo); // Schedules [foo] in front of other events. } main() { foo(); }
Runs body
in its own zone.
If onError
is non-null the zone is considered an error zone. All uncaught errors, synchronous or asynchronous, in the zone are caught and handled by the callback.
The onDone
handler (if non-null) is invoked when the zone has no more outstanding callbacks. Deprecated: this method is less useful than it seems, because it assumes that every registered callback is always invoked. There are, however, many valid reasons not to complete futures or to abort a future-chain. In general it is a bad idea to rely on onDone
.
The onRunAsync
handler (if non-null) is invoked when the body
executes runAsync
. The handler is invoked in the outer zone and can therefore execute runAsync
without recursing. The given callback must be executed eventually. Otherwise the nested zone will not complete. It must be executed only once.
Examples:
runZonedExperimental(() { new Future(() { throw "asynchronous error"; }); }, onError: print); // Will print "asynchronous error".The following example prints "1", "2", "3", "4" in this order.
runZonedExperimental(() { print(1); new Future.value(3).then(print); }, onDone: () { print(4); }); print(2);Errors may never cross error-zone boundaries. This is intuitive for leaving a zone, but it also applies for errors that would enter an error-zone. Errors that try to cross error-zone boundaries are considered uncaught.
var future = new Future.value(499); runZonedExperimental(() { future = future.then((_) { throw "error in first error-zone"; }); runZonedExperimental(() { future = future.catchError((e) { print("Never reached!"); }); }, onError: (e) { print("unused error handler"); }); }, onError: (e) { print("catches error of first error-zone."); });The following example prints the stack trace whenever a callback is registered using
runAsync
(which is also used by Completer
s and StreamController
s.
printStackTrace() { try { throw 0; } catch(e, s) { print(s); } } runZonedExperimental(body, onRunAsync: (callback) { printStackTrace(); runAsync(callback); });
A way to produce Future objects and to complete them later with a value or error.
If you already have a Future, you probably don't need a Completer. Instead, you can usually use Future.then
, which returns a Future:
Future doStuff(){ return someAsyncOperation().then((result) { // Do something. }); }If you do need to create a Future from scratch—for example, when you're converting a callback-based API into a Future-based one—you can use a Completer as follows:
Class AsyncOperation { Completer _completer = new Completer(); Future<T> doOperation() { _startOperation(); return _completer.future; // Send future object back to client. } // Something calls this when the value is ready. _finishOperation(T result) { _completer.complete(result); } // If something goes wrong, call this. _errorHappened(error) { _completer.completeError(error); } }
The future that will contain the result provided to this completer.
Whether the future has been completed.
Creates a completer whose future is completed asynchronously, sometime after complete
is called on it. This allows a call to complete
to be in the middle of other code, without running an unknown amount of future completion and then
callbacks synchronously at the point that complete
is called.
Example:
var completer = new Completer.sync(); completer.future.then((_) { bar(); }); // The completion is the result of the asynchronous onDone event. // However, there is code executed after the call to complete, // but before completer.future runs its completion callback. stream.listen(print, onDone: () { completer.complete("done"); foo(); // In this case, foo() runs before bar(). });
Completes the future synchronously.
This constructor should be avoided unless the completion of the future is known to be the final result of another asynchronous operation. If in doubt use the default Completer
constructor.
Example:
var completer = new Completer.sync(); // The completion is the result of the asynchronous onDone event. // No other operation is performed after the completion. It is safe // to use the Completer.sync constructor. stream.listen(print, onDone: () { completer.complete("done"); });Bad example. Do not use this code. Only for illustrative purposes:
var completer = new Completer.sync(); completer.future.then((_) { bar(); }); // The completion is the result of the asynchronous onDone event. // However, there is still code executed after the completion. This // operation is *not* safe. stream.listen(print, onDone: () { completer.complete("done"); foo(); // In this case, foo() runs after bar(). });
Completes future
with the supplied values.
All listeners on the future are informed about the value.
Complete future
with an error.
Completing a future with an error indicates that an exception was thrown while trying to produce a value.
The argument exception
must not be null
.
Indicates that loading of libraryName is deferred.
Applies to library imports, when used as metadata.
Example usage:
@lazy import 'foo.dart' as foo; const lazy = const DeferredLibrary('com.example.foo'); void main() { foo.method(); // Throws a NoSuchMethodError, foo is not loaded yet. lazy.load().then(onFooLoaded); } void onFooLoaded(_) { foo.method(); }
Ensure that libraryName
has been loaded.
The value of the returned future is true if this invocation of load
caused the library to be loaded.
An interface that abstracts creation or handling of Stream
events.
Create a data event
Create an async error.
Request a stream to close.
Stream that transforms another stream by intercepting and replacing events.
This Stream
is a transformation of a source stream. Listening on this stream is the same as listening on the source stream, except that events are intercepted and modified by a StreamEventTransformer
before becoming events on this stream.
Adds a subscription to this stream.
On each data event from this stream, the subscriber's onData
handler is called. If onData
is null, nothing happens.
On errors from this stream, the onError
handler is given a object describing the error.
If this stream closes, the onDone
handler is called.
If cancelOnError
is true, the subscription is ended when the first error is reported. The default is false.
An object representing a delayed computation.
A Future
is used to obtain a not yet available value, or error, sometime in the future. Receivers of a Future
can register callbacks that handle the value or error once it is available. For example:
Future<int> future = getFuture(); future.then((value) => handleValue(value)) .catchError((error) => handleError(error));A
Future
can be completed in two ways: with a value ("the future succeeds") or with an error ("the future fails"). Users can install callbacks for each case. The result of registering a pair of callbacks is a new Future (the "successor") which in turn is completed with the result of invoking the corresponding callback. The successor is completed with an error if the invoked callback throws. For example:
Future<int> successor = future.then((int value) { // Invoked when the future is completed with a value. return 42; // The successor is completed with the value 42. }, onError: (e) { // Invoked when the future is completed with an error. if (canHandle(e)) { return 499; // The successor is completed with the value 499. } else { throw e; // The successor is completed with the error e. } });If a future does not have a successor but is completed with an error, it forwards the error message to the global error-handler. This special casing makes sure that no error is silently dropped. However, it also means that error handlers should be installed early, so that they are present as soon as a future is completed with an error. The following example demonstrates this potential bug:
var future = getFuture(); new Timer(new Duration(milliseconds: 5), () { // The error-handler is only attached 5ms after the future has been // received. If the future fails in the mean-time it will forward the // error to the global error-handler, even though there is code (just // below) to handle the error. future.then((value) { useValue(value); }, onError: (e) { handleError(e); }); });In general we discourage registering the two callbacks at the same time, but prefer to use then() with one argument (the value handler), and to use catchError() for handling errors. The missing callbacks (the error-handler for then(), and the value-handler for catchError()), are automatically configured to "forward" the value/error. Separating value and error-handling into separate registration calls usually leads to code that is easier to reason about. In fact it makes asynchronous code very similar to synchronous code:
// Synchronous code. try { int value = foo(); return bar(value); } catch (e) { return 499; }Equivalent asynchronous code, based on futures:
Future<int> future = foo(); // foo now returns a future. future.then((int value) => bar(value)) .catchError((e) => 499);Similar to the synchronous code, the error handler (registered with catchError()) is handling the errors for exceptions coming from calls to 'foo', as well as 'bar'. This would not be the case if the error-handler was registered at the same time as the value-handler.
Futures can have more than one callback-pairs registered. Each successor is treated independently and is handled as if it was the only successor.
Creates a future containing the result of calling computation
asynchronously with Timer.run
.
if the result of executing computation
throws, the returned future is completed with the error. If a thrown value is an AsyncError
, it is used directly, instead of wrapping this error again in another AsyncError
.
If the returned value is itself a Future
, completion of the created future will wait until the returned future completes, and will then complete with the same result.
If a value is returned, it becomes the result of the created future.
Creates a future that completes after a delay.
The future will be completed after the given duration
has passed with the result of calling computation
. If the duration is 0 or less, it completes no sooner than in the next event-loop iteration.
If computation
is not given or null
then it will behave as if computation
was set to () => null
. That is, it will complete with null
.
If calling computation
throws, the created future will complete with the error.
See Completer
s, for futures with values that are computed asynchronously.
A future that completes with an error in the next event-loop iteration.
See Completer
to create a Future and complete it later.
Creates a future containing the result of immediately calling computation
.
If calling computation
throws, the returned future is completed with the error. If a thrown value is an AsyncError
, it is used directly, instead of wrapping this error again in another AsyncError
.
If the returned value is itself a Future
, completion of the created future will wait until the returned future completes, and will then complete with the same result.
A future whose value is available in the next event-loop iteration.
If value
is not a Future
, using this constructor is equivalent to new Future<T>.sync(() => value)
.
See Completer
to create a Future and complete it later.
Creates a Stream
that sends this
' completion value, data or error, to its subscribers. The stream closes after the completion value.
Handles errors emitted by this Future
.
Returns a new Future
f
.
When this
completes with a value, the value is forwarded to f
unmodified. That is, f
completes with the same value.
When this
completes with an error, test
is called with the error's value. If the invocation returns true
, onError
is called with the error. The result of onError
is handled exactly the same as for then
's onError
.
If test
returns false, the exception is not handled by onError
, but is thrown unmodified, thus forwarding it to f
.
If test
is omitted, it defaults to a function that always returns true.
Example:
foo .catchError(..., test: (e) => e is ArgumentError) .catchError(..., test: (e) => e is NoSuchMethodError) .then((v) { ... });This method is equivalent to:
Future catchError(onError(error), {bool test(error)}) { this.then((v) => v, // Forward the value. // But handle errors, if the [test] succeeds. onError: (e) { if (test == null || test(e)) { return onError(e); } throw e; }); }
Perform an async operation for each element of the iterable, in turn.
Runs f
for each element in input
in order, moving to the next element only when the Future
returned by f
completes. Returns a Future
that completes when all elements have been processed.
The return values of all Future
s are discarded. Any errors will cause the iteration to stop and will be piped through the returned Future
.
When this future completes with a value, then onValue
is called with this value. If this
future is already completed then the invocation of onValue
is delayed until the next event-loop iteration.
Returns a new Future
f
which is completed with the result of invoking onValue
(if this
completes with a value) or onError
(if this
completes with an error).
If the invoked callback throws an exception, the returned future f
is completed with the error.
If the invoked callback returns a Future
f2
then f
and f2
are chained. That is, f
is completed with the completion value of f2
.
If onError
is not given, it is equivalent to (e) { throw e; }
. That is, it forwards the error to f
.
In most cases, it is more readable to use catchError
separately, possibly with a test
parameter, instead of handling both value and error in a single then
call.
Wait for all the given futures to complete and collect their values.
Returns a future which will complete once all the futures in a list are complete. If any of the futures in the list completes with an error, the resulting future also completes with an error. Otherwise the value of the returned future will be a list of all the values that were produced.
Register a function to be called when this future completes.
The action
function is called when this future completes, whether it does so with a value or with an error.
This is the asynchronous equivalent of a "finally" block.
The future returned by this call, f
, will complete the same way as this future unless an error occurs in the action
call, or in a Future
returned by the action
call. If the call to action
does not return a future, its return value is ignored.
If the call to action
throws, then f
is completed with the thrown error.
If the call to action
returns a Future
, f2
, then completion of f
is delayed until f2
completes. If f2
completes with an error, that will be the result of f
too. The value of f2
is always ignored.
This method is equivalent to:
Future<T> whenComplete(action()) { this.then((v) { var f2 = action(); if (f2 is Future) return f2.then((_) => v); return v }, onError: (e) { var f2 = action(); if (f2 is Future) return f2.then((_) { throw e; }); throw e; }); }
A source of asynchronous data events.
A Stream provides a sequence of events. Each event is either a data event or an error event, representing the result of a single computation. When the Stream is exhausted, it may send a single "done" event.
You can listen() on a stream to receive the events it sends. When you listen, you receive a StreamSubscription
object that can be used to stop listening, or to temporarily pause events from the stream.
When an event is fired, the listeners at that time are informed. If a listener is added while an event is being fired, the change will only take effect after the event is completely fired. If a listener is canceled, it immediately stops receiving events.
When the "done" event is fired, subscribers are unsubscribed before receiving the event. After the event has been sent, the stream has no subscribers. Adding new subscribers after this point is allowed, but they will just receive a new "done" event as soon as possible.
Streams always respect "pause" requests. If necessary they need to buffer their input, but often, and preferably, they can simply request their input to pause too.
There are two kinds of streams: The normal "single-subscription" streams and "broadcast" streams.
A single-subscription stream allows only a single listener at a time. It holds back events until it gets a listener, and it may exhaust itself when the listener is unsubscribed, even if the stream wasn't done.
Single-subscription streams are generally used for streaming parts of contiguous data like file I/O.
A broadcast stream allows any number of listeners, and it fires its events when they are ready, whether there are listeners or not.
Broadcast streams are used for independent events/observers.
The default implementation of isBroadcast returns false. A broadcast stream inheriting from Stream
must override isBroadcast to return true
.
Returns the first element of the stream.
Stops listening to the stream after the first element has been received.
If an error event occurs before the first data event, the resulting future is completed with that error.
If this stream is empty (a done event occurs before the first data event), the resulting future completes with a StateError
.
Except for the type of the error, this method is equivalent to this.elementAt(0)
.
Reports whether this stream is a broadcast stream.
Reports whether this stream contains any elements.
Returns the last element of the stream.
If an error event occurs before the first data event, the resulting future is completed with that error.
If this stream is empty (a done event occurs before the first data event), the resulting future completes with a StateError
.
Counts the elements in the stream.
Returns the single element.
If this
is empty or has more than one element throws a StateError
.
Creates a new single-subscription stream from the future.
When the future completes, the stream will fire one event, either data or error, and then close with a done-event.
Creates a single-subscription stream that gets its data from data
.
If iterating data
throws an error, the stream ends immediately with that error. No done event will be sent (iteration is not complete), but no further data events will be generated either, since iteration cannot continue.
Creates a stream that repeatedly emits events at period
intervals.
The event values are computed by invoking computation
. The argument to this callback is an integer that starts with 0 and is incremented for every event.
If computation
is omitted the event values will all be null
.
Checks whether test
accepts any element provided by this stream.
Completes the Future
when the answer is known. If this stream reports an error, the Future
will report that error.
Returns a multi-subscription stream that produces the same events as this.
If this stream is already a broadcast stream, it is returned unmodified.
If this stream is single-subscription, return a new stream that allows multiple subscribers. It will subscribe to this stream when its first subscriber is added, and will stay subscribed until this stream ends, or a callback cancels the subscription.
If onListen
is provided, it is called with a subscription-like object that represents the underlying subscription to this stream. It is possible to pause, resume or cancel the subscription during the call to onListen
. It is not possible to change the event handlers, including using StreamSubscription.asFuture
.
If onCancel
is provided, it is called in a similar way to onListen
when the returned stream stops having listener. If it later gets a new listener, the onListen
function is called again.
Use the callbacks, for example, for pausing the underlying subscription while having no subscribers to prevent losing events, or canceling the subscription when there are no listeners.
Checks whether needle
occurs in the elements provided by this stream.
Completes the Future
when the answer is known. If this stream reports an error, the Future
will report that error.
Skips data events if they are equal to the previous data event.
The returned stream provides the same events as this stream, except that it never provides two consequtive data events that are equal.
Equality is determined by the provided equals
method. If that is omitted, the '==' operator on the last provided data element is used.
Discards all data on the stream, but signals when it's done or an error occured.
When subscribing using drain
, cancelOnError will be true. This means that the future will complete with the first error on the stream and then cancel the subscription.
In case of a done
event the future completes with the given futureValue
.
Returns the value of the index
th data event of this stream.
Stops listening to the stream after a value has been found.
If an error event occurs before the value is found, the future completes with this error.
If a done event occurs before the value is found, the future completes with a RangeError
.
Checks whether test
accepts all elements provided by this stream.
Completes the Future
when the answer is known. If this stream reports an error, the Future
will report that error.
Creates a new stream from this stream that converts each element into zero or more events.
Each incoming event is converted to an Iterable
of new events, and each of these new events are then sent by the returned stream in order.
Finds the first element of this stream matching test
.
Returns a future that is filled with the first element of this stream that test
returns true for.
If no such element is found before this stream is done, and a defaultValue
function is provided, the result of calling defaultValue
becomes the value of the future.
If an error occurs, or if this stream ends without finding a match and with no defaultValue
function provided, the future will receive an error.
Reduces a sequence of values by repeatedly applying combine
.
Executes action
on each data event of the stream.
Completes the returned Future
when all events of the stream have been processed. Completes the future with an error if the stream has an error event, or if action
throws.
Creates a wrapper Stream that intercepts some errors from this stream.
If this stream sends an error that matches test
, then it is intercepted by the handle
function.
An AsyncError
e
is matched by a test function if test(e)
returns true. If test
is omitted, every error is considered matching.
If the error is intercepted, the handle
function can decide what to do with it. It can throw if it wants to raise a new (or the same) error, or simply return to make the stream forget the error.
If you need to transform an error into a data event, use the more generic Stream.transform
to handle the event by writing a data event to the output sink
Collects string of data events' string representations.
If separator
is provided, it is inserted between any two elements.
Any error in the stream causes the future to complete with that error. Otherwise it completes with the collected string when the "done" event arrives.
Finds the last element in this stream matching test
.
As firstWhere
, except that the last matching element is found. That means that the result cannot be provided before this stream is done.
Adds a subscription to this stream.
On each data event from this stream, the subscriber's onData
handler is called. If onData
is null, nothing happens.
On errors from this stream, the onError
handler is given a object describing the error.
If this stream closes, the onDone
handler is called.
If cancelOnError
is true, the subscription is ended when the first error is reported. The default is false.
Creates a new stream that converts each element of this stream to a new value using the convert
function.
Binds this stream as the input of the provided StreamConsumer
.
Reduces a sequence of values by repeatedly applying combine
.
Finds the single element in this stream matching test
.
Like lastMatch
, except that it is an error if more than one matching element occurs in the stream.
Skips the first count
data events from this stream.
Skip data events from this stream while they are matched by test
.
Error and done events are provided by the returned stream unmodified.
Starting with the first data event where test
returns false for the event data, the returned stream will have the same events as this stream.
Provides at most the first n
values of this stream.
Forwards the first n
data events of this stream, and all error events, to the returned stream, and ends with a done event.
If this stream produces fewer than count
values before it's done, so will the returned stream.
Forwards data events while test
is successful.
The returned stream provides the same events as this stream as long as test
returns true
for the event data. The stream is done when either this stream is done, or when this stream first provides a value that test
doesn't accept.
Collects the data of this stream in a List
.
Collects the data of this stream in a Set
.
Chains this stream as the input of the provided StreamTransformer
.
Returns the result of streamTransformer.bind
itself.
Creates a new stream from this stream that discards some data events.
The new stream sends the same error and done events as this stream, but it only sends the data events that satisfy the test
.
The target of a Stream.pipe
call.
The Stream.pipe
call will pass itself to this object, and then return the resulting Future
. The pipe should complete the future when it's done.
A controller with the stream it controls.
This controller allows sending data, error and done events on its stream. This class can be used to create a simple stream that others can listen on, and to push events to that stream.
It's possible to check whether the stream is paused or not, and whether it has subscribers or not, as well as getting a callback when either of these change.
If the stream starts or stops having listeners (first listener subscribing, last listener unsubscribing), the onSubscriptionStateChange
callback is notified as soon as possible. If the subscription stat changes during an event firing or a callback being executed, the change will not be reported until the current event or callback has finished. If the pause state has also changed during an event or callback, only the subscription state callback is notified.
If the subscriber state has not changed, but the pause state has, the onPauseStateChange
callback is notified as soon as possible, after firing a current event or completing another callback. This happens if the stream is not paused, and a listener pauses it, or if the stream has been resumed from pause and has no pending events. If the listeners resume a paused stream while it still has queued events, the controller will still consider the stream paused until all queued events have been dispatched.
Whether to invoke a callback depends only on the state before and after a stream action, for example firing an event. If the state changes multiple times during the action, and then ends up in the same state as before, no callback is performed.
If listeners are added after the stream has completed (sent a "done" event), the listeners will be sent a "done" event eventually, but they won't affect the stream at all, and won't trigger callbacks. From the controller's point of view, the stream is completely inert when has completed.
Whether there is a subscriber on the Stream
.
Whether the stream is closed for adding more events.
If true, the "done" event might not have fired yet, but it has been scheduled, and it is too late to add more events.
Whether the subscription would need to buffer events.
This is the case if the controller's stream has a listener and it is paused, or if it has not received a listener yet. In that case, the controller is considered paused as well.
A broadcast stream controller is never considered paused. It always forwards its events to all uncanceled listeners, if any, and let them handle their own pausing.
Returns a view of this object that only exposes the StreamSink
interface.
The stream that this controller is controlling.
A controller with a stream
that supports only one single subscriber.
If sync
is true, events may be passed directly to the stream's listener during an add
, addError
or close
call. If sync
is false, the event will be passed to the listener at a later time, after the code creating the event has returned.
The controller will buffer all incoming events until the subscriber is registered.
The onPause
function is called when the stream becomes paused. onResume
is called when the stream resumed.
The onListen
callback is called when the stream receives its listener and onCancel
when the listener ends its subscription.
If the stream is canceled before the controller needs new data the onResume
call might not be executed.
A controller where stream
can be listened to more than once.
The Stream
returned by stream
is a broadcast stream. It can be listened to more than once.
The controller distributes any events to all currently subscribed listeners. It is not allowed to call add
, addError
, or close
before a previous call has returned.
If sync
is true, events may be passed directly to the stream's listener during an add
, addError
or close
call. If sync
is false, the event will be passed to the listener at a later time, after the code creating the event has returned.
Each listener is handled independently, and if they pause, only the pausing listener is affected. A paused listener will buffer events internally until unpaused or canceled.
If sync
is false, no guarantees are given with regard to when multiple listeners get the events, except that each listener will get all events in the correct order. If two events are sent on an async controller with two listeners, one of the listeners may get both events before the other listener gets any. A listener must be subscribed both when the event is initiated (that is, when add
is called) and when the event is later delivered, in order to get the event.
The onListen
callback is called when the first listener is subscribed, and the onCancel
is called when there are no longer any active listeners. If a listener is added again later, after the onCancel
was called, the onListen
will be called again.
Send or enqueue an error event.
Also allows an objection stack trace object, on top of what EventSink
allows.
Base class for transformers that modifies stream events.
A StreamEventTransformer
transforms incoming Stream events of one kind into outgoing events of (possibly) another kind.
Subscribing on the stream returned by bind() is the same as subscribing on the source stream, except that events are passed through the transformer
before being emitted. The transformer may generate any number and types of events for each incoming event. Pauses on the returned subscription are forwarded to this stream.
An example that duplicates all data events:
class DoubleTransformer<T> extends StreamEventTransformer<T, T> { void handleData(T data, EventSink<T> sink) { sink.add(value); sink.add(value); } } someTypeStream.transform(new DoubleTransformer<Type>());The default implementations of the "handle" methods forward the events unmodified. If using the default handleData() the generic type
T
needs to be assignable to S
.
Act on incoming data event.
The method may generate any number of events on the sink, but should not throw.
Act on incoming done event.
The method may generate any number of events on the sink, but should not throw.
Act on incoming error event.
The method may generate any number of events on the sink, but should not throw.
An Iterable
like interface for the values of a Stream
.
This wraps a Stream
and a subscription on the stream. It listens on the stream, and completes the future returned by moveNext() when the next value becomes available.
NOTICE: This is a tentative design. This class may change.
The current value of the stream.
Only valid when the future returned by moveNext
completes with true
as value, and only until the next call to moveNext
.
Create a StreamIterator
on stream
.
Cancels the stream iterator (and the underlying stream subscription) early.
The stream iterator is automatically canceled if the moveNext
future completes with either false
or an error.
If a moveNext
call has been made, it will complete with false
as value, as will all further calls to moveNext
.
If you need to stop listening for values before the stream iterator is automatically closed, you must call cancel
to ensure that the stream is properly closed.
Wait for the next stream value to be available.
It is not allowed to call this function again until the future has completed. If the returned future completes with anything except true
, the iterator is done, and no new value will ever be available.
The future may complete with an error, if the stream produces an error.
A StreamSink
unifies the asynchronous methods from StreamConsumer
and the synchronous methods from EventSink
.
The EventSink
methods can't be used while the addStream
is called. As soon as the addStream
's Future
completes with a value, the EventSink
methods can be used again.
If addStream
is called after any of the EventSink
methods, it'll be delayed until the underlying system has consumed the data added by the EventSink
methods.
When EventSink
methods are used, the done Future
can be used to catch any errors.
The done
Future completes with the same values as close
, except for the following case:
EventSink
were called, resulting in andone
future will complete with that error
Close the StreamSink
. It'll return the done
Future.
A control object for the subscription on a Stream
.
When you subscribe on a Stream
using Stream.listen
, a StreamSubscription
object is returned. This object is used to later unsubscribe again, or to temporarily pause the stream's events.
Returns true if the StreamSubscription
is paused.
Returns a future that handles the onDone
and onError
callbacks.
This method overwrites the existing onDone
and onError
callbacks with new ones that complete the returned future.
In case of an error the subscription will automatically cancel (even when it was listening with cancelOnError
set to false
).
In case of a done
event the future completes with the given futureValue
.
Cancels this subscription. It will no longer receive events.
If an event is currently firing, this unsubscription will only take effect after all subscribers have received the current event.
Set or override the data event handler of this subscription.
Set or override the done event handler of this subscription.
Set or override the error event handler of this subscription.
Request that the stream pauses events until further notice.
If resumeSignal
is provided, the stream will undo the pause when the future completes. If the future completes with an error, it will not be handled!
A call to resume
will also undo a pause.
If the subscription is paused more than once, an equal number of resumes must be performed to resume the stream.
Resume after a pause.
The target of a Stream.transform
call.
The Stream.transform
call will pass itself to this object and then return the resulting stream.
Create a StreamTransformer
that delegates events to the given functions.
This is actually a StreamEventTransformer
where the event handling is performed by the function arguments. If an argument is omitted, it acts as the corresponding default method from StreamEventTransformer
.
Example use:
stringStream.transform(new StreamTransformer<String, String>( handleData: (String value, EventSink<String> sink) { sink.add(value); sink.add(value); // Duplicate the incoming events. }));
Stream
wrapper that only exposes the Stream
interface.
Returns a multi-subscription stream that produces the same events as this.
If this stream is already a broadcast stream, it is returned unmodified.
If this stream is single-subscription, return a new stream that allows multiple subscribers. It will subscribe to this stream when its first subscriber is added, and will stay subscribed until this stream ends, or a callback cancels the subscription.
If onListen
is provided, it is called with a subscription-like object that represents the underlying subscription to this stream. It is possible to pause, resume or cancel the subscription during the call to onListen
. It is not possible to change the event handlers, including using StreamSubscription.asFuture
.
If onCancel
is provided, it is called in a similar way to onListen
when the returned stream stops having listener. If it later gets a new listener, the onListen
function is called again.
Use the callbacks, for example, for pausing the underlying subscription while having no subscribers to prevent losing events, or canceling the subscription when there are no listeners.
Adds a subscription to this stream.
On each data event from this stream, the subscriber's onData
handler is called. If onData
is null, nothing happens.
On errors from this stream, the onError
handler is given a object describing the error.
If this stream closes, the onDone
handler is called.
If cancelOnError
is true, the subscription is ended when the first error is reported. The default is false.
A count-down timer that can be configured to fire once or repeatedly.
The timer counts down from the specified duration to 0. When the timer reaches 0, the timer invokes the specified callback function. Use a periodic timer to repeatedly count down the same interval.
A negative duration is treated the same as a duration of 0. If the duration is statically known to be 0, consider using run().
Frequently the duration is either a constant or computed as in the following example (taking advantage of the multiplication operator of the Duration
class):
const TIMEOUT = const Duration(seconds: 3); const ms = const Duration(milliseconds: 1); startTimeout([int milliseconds]) { var duration = milliseconds == null ? TIMEOUT : ms * milliseconds; return new Timer(duration, handleTimeout); } ... void handleTimeout() { // callback function ... }Note: If Dart code using Timer is compiled to JavaScript, the finest granularity available in the browser is 4 milliseconds.
See Stopwatch
for measuring elapsed time.
Returns whether the timer is still active.
A non-periodic timer is active if the callback has not been executed, and the timer has not been canceled.
A periodic timer is active if it has not been canceled.
Creates a new timer.
The callback
function is invoked after the given duration
.
Creates a new repeating timer.
The callback
is invoked repeatedly with duration
intervals until canceled with the cancel
function.
Cancels the timer.
Runs the given callback
asynchronously as soon as possible.
This function is equivalent to new Timer(Duration.ZERO, callback)
.