dart.async


Functions
getAttachedStackTrace(dynamic o): dynamic
runAsync( callback): void
runZonedExperimental( body, onRunAsync, onError, onDone): dynamic
Classes
Completer
DeferredLibrary
EventSink
EventTransformStream
Future
Stream
StreamConsumer
StreamController
StreamEventTransformer
StreamIterator
StreamSink
StreamSubscription
StreamTransformer
StreamView
Timer

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/).

Functions

static dynamic getAttachedStackTrace(dynamic o)

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.

static void runAsync( callback)

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();
}

static dynamic runZonedExperimental( body, onRunAsync, onError, onDone)

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 Completers and StreamControllers.

printStackTrace() { try { throw 0; } catch(e, s) { print(s); } }
runZonedExperimental(body, onRunAsync: (callback) {
  printStackTrace();
  runAsync(callback);
});


Abstract class Completer

Fields
future: Future
isCompleted: bool
Getters and Setters
future: Future<dynamic>
isCompleted: bool
Constructors
Completer()
Completer.sync()
Methods
complete(T value): void
completeError(Object exception, Object stackTrace): void

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);
  }
}

Fields

final Future future
final bool isCompleted

Getters and Setters

Future<dynamic> get future

The future that will contain the result provided to this completer.

bool get isCompleted

Whether the future has been completed.

Constructors

factory Completer()

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().
});

factory Completer.sync()

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().
});

Methods

void complete(T value)

Completes future with the supplied values.

All listeners on the future are informed about the value.

void completeError(Object exception, Object stackTrace)

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.


Class DeferredLibrary

Fields
libraryName: String
uri: String
Constructors
DeferredLibrary(String libraryName, String uri)
Methods
load(): Future<bool>

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();
}

Fields

final String libraryName
final String uri

Constructors

DeferredLibrary(String libraryName, String uri)

Methods

Future<bool> load()

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.


Abstract class EventSink

Constructors
EventSink()
Methods
add(T event): void
addError(dynamic errorEvent): void
close(): void

An interface that abstracts creation or handling of Stream events.

Constructors

EventSink()

Methods

void add(T event)

Create a data event

void addError(dynamic errorEvent)

Create an async error.

void close()

Request a stream to close.


Class EventTransformStream extends Stream<T>

Constructors
EventTransformStream(Stream<S> source, StreamEventTransformer<S, T> transformer)
Methods
listen(<S, T> onData, <S, T> onError, <S, T> onDone, bool cancelOnError): StreamSubscription<T>

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.

Constructors

EventTransformStream(Stream<S> source, StreamEventTransformer<S, T> transformer)

Methods

StreamSubscription<T> listen(<S, T> onData, <S, T> onError, <S, T> onDone, bool cancelOnError)

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.


Abstract class Future

Constructors
Future(<T> computation)
Future.delayed(Duration duration, <T> computation)
Future.error(dynamic error, Object stackTrace)
Future.sync(<T> computation)
Future.value(dynamic value)
Methods
asStream(): Stream<T>
catchError(<T> onError, <T> test): Future<dynamic>
forEach(Iterable<dynamic> input, <T> f): Future<dynamic>
then(<T> onValue, <T> onError): Future<dynamic>
wait(Iterable<Future<dynamic>> futures): Future<List<dynamic>>
whenComplete(<T> action): Future<T>

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.

Constructors

factory Future(<T> computation)

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.

factory Future.delayed(Duration duration, <T> computation)

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 Completers, for futures with values that are computed asynchronously.

factory Future.error(dynamic error, Object stackTrace)

A future that completes with an error in the next event-loop iteration.

See Completer to create a Future and complete it later.

factory Future.sync(<T> computation)

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.

factory Future.value(dynamic value)

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.

Methods

Stream<T> asStream()

Creates a Stream that sends this' completion value, data or error, to its subscribers. The stream closes after the completion value.

Future<dynamic> catchError(<T> onError, <T> test)

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;
            });
}

static Future<dynamic> forEach(Iterable<dynamic> input, <T> f)

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 Futures are discarded. Any errors will cause the iteration to stop and will be piped through the returned Future.

Future<dynamic> then(<T> onValue, <T> onError)

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.

static Future<List<dynamic>> wait(Iterable<Future<dynamic>> futures)

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.

Future<T> whenComplete(<T> action)

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;
            });
}


Abstract class Stream

Fields
first: Future
isBroadcast: bool
isEmpty: Future
last: Future
length: Future
single: Future
Getters and Setters
first: Future<T>
isBroadcast: bool
isEmpty: Future<bool>
last: Future<T>
length: Future<int>
single: Future<T>
Constructors
Stream()
Stream.fromFuture(Future<T> future)
Stream.fromIterable(Iterable<T> data)
Stream.periodic(Duration period, <T> computation)
Methods
any(<T> test): Future<bool>
asBroadcastStream(<T> onListen, <T> onCancel): Stream<T>
contains(Object needle): Future<bool>
distinct(<T> equals): Stream<T>
drain(dynamic futureValue): Future<dynamic>
elementAt(int index): Future<T>
every(<T> test): Future<bool>
expand(<T> convert): Stream<dynamic>
firstWhere(<T> test, <T> defaultValue): Future<dynamic>
fold(dynamic initialValue, <T> combine): Future<dynamic>
forEach(<T> action): Future<dynamic>
handleError(<T> handle, <T> test): Stream<T>
join(String separator): Future<String>
lastWhere(<T> test, <T> defaultValue): Future<dynamic>
listen(<T> onData, <T> onError, <T> onDone, bool cancelOnError): StreamSubscription<T>
map(<T> convert): Stream<dynamic>
pipe(StreamConsumer<T> streamConsumer): Future<dynamic>
reduce(<T> combine): Future<T>
singleWhere(<T> test): Future<T>
skip(int count): Stream<T>
skipWhile(<T> test): Stream<T>
take(int count): Stream<T>
takeWhile(<T> test): Stream<T>
toList(): Future<List<T>>
toSet(): Future<Set<T>>
transform(StreamTransformer<T, dynamic> streamTransformer): Stream<dynamic>
where(<T> test): Stream<T>

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.

Fields

final Future first
final bool isBroadcast
final Future isEmpty
final Future last
final Future length
final Future single

Getters and Setters

Future<T> get first

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).

bool get isBroadcast

Reports whether this stream is a broadcast stream.

Future<bool> get isEmpty

Reports whether this stream contains any elements.

Future<T> get last

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.

Future<int> get length

Counts the elements in the stream.

Future<T> get single

Returns the single element.

If this is empty or has more than one element throws a StateError.

Constructors

Stream()
factory Stream.fromFuture(Future<T> future)

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.

factory Stream.fromIterable(Iterable<T> data)

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.

factory Stream.periodic(Duration period, <T> computation)

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.

Methods

Future<bool> any(<T> test)

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.

Stream<T> asBroadcastStream(<T> onListen, <T> onCancel)

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.

Future<bool> contains(Object needle)

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.

Stream<T> distinct(<T> equals)

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.

Future<dynamic> drain(dynamic futureValue)

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.

Future<T> elementAt(int index)

Returns the value of the indexth 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.

Future<bool> every(<T> test)

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.

Stream<dynamic> expand(<T> convert)

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.

Future<dynamic> firstWhere(<T> test, <T> defaultValue)

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.

Future<dynamic> fold(dynamic initialValue, <T> combine)

Reduces a sequence of values by repeatedly applying combine.

Future<dynamic> forEach(<T> action)

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.

Stream<T> handleError(<T> handle, <T> test)

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

Future<String> join(String separator)

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.

Future<dynamic> lastWhere(<T> test, <T> defaultValue)

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.

StreamSubscription<T> listen(<T> onData, <T> onError, <T> onDone, bool cancelOnError)

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.

Stream<dynamic> map(<T> convert)

Creates a new stream that converts each element of this stream to a new value using the convert function.

Future<dynamic> pipe(StreamConsumer<T> streamConsumer)

Binds this stream as the input of the provided StreamConsumer.

Future<T> reduce(<T> combine)

Reduces a sequence of values by repeatedly applying combine.

Future<T> singleWhere(<T> test)

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.

Stream<T> skip(int count)

Skips the first count data events from this stream.

Stream<T> skipWhile(<T> test)

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.

Stream<T> take(int count)

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.

Stream<T> takeWhile(<T> test)

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.

Future<List<T>> toList()

Collects the data of this stream in a List.

Future<Set<T>> toSet()

Collects the data of this stream in a Set.

Stream<dynamic> transform(StreamTransformer<T, dynamic> streamTransformer)

Chains this stream as the input of the provided StreamTransformer.

Returns the result of streamTransformer.bind itself.

Stream<T> where(<T> test)

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.


Abstract class StreamConsumer

Constructors
StreamConsumer()
Methods
addStream(Stream<S> stream): Future<dynamic>
close(): Future<dynamic>

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.

Constructors

StreamConsumer()

Methods

Future<dynamic> addStream(Stream<S> stream)
Future<dynamic> close()

Abstract class StreamController implements StreamSink<T>

Fields
hasListener: bool
isClosed: bool
isPaused: bool
sink: StreamSink
stream: Stream
Getters and Setters
hasListener: bool
isClosed: bool
isPaused: bool
sink: StreamSink<T>
stream: Stream<T>
Constructors
StreamController(<T> onListen, <T> onPause, <T> onResume, <T> onCancel, bool sync)
StreamController.broadcast(<T> onListen, <T> onCancel, bool sync)
Methods
addError(Object error, Object stackTrace): void

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.

Fields

final bool hasListener
final bool isClosed
final bool isPaused
final StreamSink sink
final Stream stream

Getters and Setters

bool get hasListener

Whether there is a subscriber on the Stream.

bool get isClosed

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.

bool get isPaused

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.

StreamSink<T> get sink

Returns a view of this object that only exposes the StreamSink interface.

Stream<T> get stream

The stream that this controller is controlling.

Constructors

factory StreamController(<T> onListen, <T> onPause, <T> onResume, <T> onCancel, bool sync)

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.

factory StreamController.broadcast(<T> onListen, <T> onCancel, bool sync)

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.

Methods

void addError(Object error, Object stackTrace)

Send or enqueue an error event.

Also allows an objection stack trace object, on top of what EventSink allows.


Abstract class StreamEventTransformer implements StreamTransformer<S, T>

Constructors
StreamEventTransformer()
Methods
bind(Stream<S> source): Stream<T>
handleData(S event, EventSink<T> sink): void
handleDone(EventSink<T> sink): void
handleError(dynamic error, EventSink<T> sink): void

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.

Constructors

StreamEventTransformer()

Methods

Stream<T> bind(Stream<S> source)
void handleData(S event, EventSink<T> sink)

Act on incoming data event.

The method may generate any number of events on the sink, but should not throw.

void handleDone(EventSink<T> sink)

Act on incoming done event.

The method may generate any number of events on the sink, but should not throw.

void handleError(dynamic error, EventSink<T> sink)

Act on incoming error event.

The method may generate any number of events on the sink, but should not throw.


Abstract class StreamIterator

Fields
current: T
Getters and Setters
current: T
Constructors
StreamIterator(Stream<T> stream)
Methods
cancel(): void
moveNext(): Future<bool>

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.

Fields

final T current

Getters and Setters

T get current

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.

Constructors

factory StreamIterator(Stream<T> stream)

Create a StreamIterator on stream.

Methods

void cancel()

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.

Future<bool> moveNext()

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.


Abstract class StreamSink implements StreamConsumer<S>, EventSink<S>

Fields
done: Future
Getters and Setters
done: Future<dynamic>
Constructors
StreamSink()
Methods
close(): Future<dynamic>

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.

When close() is called, it will return the done Future.

Fields

final Future done

Getters and Setters

Future<dynamic> get done

The done Future completes with the same values as close, except for the following case:

  • The synchronous methods of EventSink were called, resulting in an
error. If there is no active future (like from an addStream call), the done future will complete with that error

Constructors

StreamSink()

Methods

Future<dynamic> close()

Close the StreamSink. It'll return the done Future.


Abstract class StreamSubscription

Fields
isPaused: bool
Getters and Setters
isPaused: bool
Constructors
StreamSubscription()
Methods
asFuture(dynamic futureValue): Future<dynamic>
cancel(): void
onData(<T> handleData): void
onDone(<T> handleDone): void
onError(<T> handleError): void
pause(Future<dynamic> resumeSignal): void
resume(): void

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.

Fields

final bool isPaused

Getters and Setters

bool get isPaused

Returns true if the StreamSubscription is paused.

Constructors

StreamSubscription()

Methods

Future<dynamic> asFuture(dynamic futureValue)

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.

void cancel()

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.

void onData(<T> handleData)

Set or override the data event handler of this subscription.

void onDone(<T> handleDone)

Set or override the done event handler of this subscription.

void onError(<T> handleError)

Set or override the error event handler of this subscription.

void pause(Future<dynamic> resumeSignal)

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.

void resume()

Resume after a pause.


Abstract class StreamTransformer

Constructors
StreamTransformer(<S, T> handleData, <S, T> handleError, <S, T> handleDone)
Methods
bind(Stream<S> stream): Stream<T>

The target of a Stream.transform call.

The Stream.transform call will pass itself to this object and then return the resulting stream.

Constructors

factory StreamTransformer(<S, T> handleData, <S, T> handleError, <S, T> handleDone)

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.
    }));

Methods

Stream<T> bind(Stream<S> stream)

Class StreamView extends Stream<T>

Fields
isBroadcast: bool
Getters and Setters
isBroadcast: bool
Constructors
StreamView(Stream<T> _stream)
Methods
asBroadcastStream(<T> onListen, <T> onCancel): Stream<T>
listen(<T> onData, <T> onError, <T> onDone, bool cancelOnError): StreamSubscription<T>

Stream wrapper that only exposes the Stream interface.

Fields

final bool isBroadcast

Getters and Setters

bool get isBroadcast

Constructors

StreamView(Stream<T> _stream)

Methods

Stream<T> asBroadcastStream(<T> onListen, <T> onCancel)

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.

StreamSubscription<T> listen(<T> onData, <T> onError, <T> onDone, bool cancelOnError)

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.


Abstract class Timer

Fields
isActive: bool
Getters and Setters
isActive: bool
Constructors
Timer(Duration duration, callback)
Timer.periodic(Duration duration, callback)
Methods
cancel(): void
run( callback): void

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.

Fields

final bool isActive

Getters and Setters

bool get isActive

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.

Constructors

factory Timer(Duration duration, callback)

Creates a new timer.

The callback function is invoked after the given duration.

factory Timer.periodic(Duration duration, callback)

Creates a new repeating timer.

The callback is invoked repeatedly with duration intervals until canceled with the cancel function.

Methods

void cancel()

Cancels the timer.

static void run( callback)

Runs the given callback asynchronously as soon as possible.

This function is equivalent to new Timer(Duration.ZERO, callback).