RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Core libraries

Futures, streams and timers

Future, Stream, stream controllers and transformers, Completer, Timer, zones and microtasks.

import 'raya:async';
33 classes193 functions and methods237 of 268 documented185 runnable examples

Overview

Support for asynchronous programming, with classes such as Future and Stream.

Futures and Streams are the fundamental building blocks of asynchronous programming in Raya. They are supported directly in the language through async and async* functions, and are available to all libraries through the raya:core library.

This library provides further tools for creating, consuming and transforming futures and streams, as well as direct access to other asynchronous primitives like Timer, scheduleMicrotask and Zone.

To use this library in your code:

import 'raya:async';

Future

A Future object represents a computation whose return value might not yet be available. The Future returns the value of the computation when it completes at some time in the future. Futures are often used for APIs that are implemented using a different thread or isolate (e.g. the asynchronous I/O operations of raya:io or HTTP requests of raya:html).

Many methods in the Raya libraries return Futures when performing tasks. For example, when binding an HttpServer to a host and port, the bind method returns a Future.

HttpServer.bind('127.0.0.1', 4444)
    .then((server) => print('${server.isBroadcast}'))
    .catchError(print);

Future.then registers a callback function that runs when the Future's operation, in this case the bind method, completes successfully. The value returned by the operation is passed into the callback function. In this example, the bind method returns the HttpServer object. The callback function prints one of its properties. Future.catchError registers a callback function that runs if an error occurs within the Future.

Stream

A Stream provides an asynchronous sequence of data. Examples of data sequences include individual events, like mouse clicks, or sequential chunks of larger data, like multiple byte lists with the contents of a file such as mouse clicks, and a stream of byte lists read from a file. The following example opens a file for reading. Stream.listen registers callback functions that run each time more data is available, an error has occurred, or the stream has finished. Further functionality is provided on Stream, implemented by calling Stream.listen to get the actual data.

Stream<List<int>> stream = File('quotes.txt').openRead();
stream.transform(utf8.decoder).forEach(print);

This stream emits a sequence of lists of bytes. The program must then handle those lists of bytes in some way. Here, the code uses a UTF-8 decoder (provided in the raya:convert library) to convert the sequence of bytes into a sequence of Raya strings.

Another common use of streams is for user-generated events in a web app: The following code listens for mouse clicks on a button.

querySelector('#myButton')!.onClick.forEach((_) => print('Click.'));

Functions and constants

Functions

unawaitedfunction
void unawaited(Future<void>? future)

Explicitly ignores a future.

Not all futures need to be awaited. If a particular future value doesn't need to be awaited, you can call unawaited(...) with it, which will avoid the lint, simply because the expression no longer has type Future. Using unawaited has no other effect. You should use unawaited to convey the intention of deliberately not waiting for the future.

If the future completes with an error, it was likely a mistake to not await it. That error will still occur and will be considered unhandled unless the same future is awaited (or otherwise handled) elsewhere too. Because of that, unawaited should only be used for futures that are expected to complete with a value. You can use FutureExtensions.ignore if you also don't want to know about errors from this future.

Example
import 'raya:async';

Future<void> log(List<String> out, String s) async => out.add(s);

Future<void> main() async {
  final out = <String>[];
  // Fire-and-forget: unawaited documents that the future is ignored on purpose.
  unawaited(log(out, 'background write'));
  out.add('main continues');
  await Future.value();
  print('order: $out');
  unawaited(null); // a null future is allowed and does nothing
  print('unawaited(null) ok');
}
Output
order: [background write, main continues]
unawaited(null) ok
void scheduleMicrotask(void Function() callback)

Runs a function 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 runs the callbacks without ever giving the Timer callback a chance to execute:

main() {
  Timer.run(() { print("executed"); });  // Will never be executed.
  foo() {
    scheduleMicrotask(foo);  // Schedules [foo] in front of other events.
  }
  foo();
}
Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  Timer.run(() => order.add('timer'));
  scheduleMicrotask(() => order.add('microtask 1'));
  scheduleMicrotask(() => order.add('microtask 2'));
  order.add('sync');
  await Future.delayed(const Duration(milliseconds: 1));
  // Microtasks run before any timer event.
  print('order: $order');
}
Output
order: [sync, microtask 1, microtask 2, timer]
runZonedfunction
R runZoned<R>(R body(), {Map<Object?, Object?>? zoneValues, ZoneSpecification? zoneSpecification, @Deprecated("Use runZonedGuarded instead") Function? onError})

Runs body in its own zone.

Creates a new zone using Zone.fork based on zoneSpecification and zoneValues, then runs body in that zone and returns the result.

Example use:

var secret = "arglebargle"; // Or a random generated string.
var result = runZoned(
    () async {
      await Future.delayed(Duration(seconds: 5), () {
        print("${Zone.current[#_secret]} glop glyf");
      });
    },
    zoneValues: {#_secret: secret},
    zoneSpecification:
        ZoneSpecification(print: (Zone self, parent, zone, String value) {
      if (value.contains(Zone.current[#_secret] as String)) {
        value = "--censored--";
      }
      parent.print(zone, value);
    }));
secret = ""; // Erase the evidence.
await result; // Wait for asynchronous computation to complete.

The new zone intercepts print and stores a value under the private symbol #_secret. The secret is available from the new Zone object, which is the Zone.current for the body, and is also the first, self, parameter to the print handler function.

If the ZoneSpecification.handleUncaughtError is set, or the deprecated onError callback is passed, the created zone will be an error zone. Asynchronous errors in futures never cross zone boundaries between zones with a different Zone.errorZone. A consequence of that behavior can be that a Future which completes as an error in the created zone will seem to never complete when used from a zone that belongs to a different error zone. Multiple attempts to use the future in a zone where the error is inaccessible will cause the error to be reported again in it's original error zone.

See runZonedGuarded in place of using the deprected onError argument. If onError is provided this function also tries to catch and handle synchronous errors from body, but may throw an error anyway returning null if the generic argument R is not nullable.

Example
import 'raya:async';

String whoAmI() => 'user=${Zone.current[#user] ?? 'nobody'}';

void main() {
  print('outside: ${whoAmI()}');
  final r = runZoned(() => whoAmI(), zoneValues: {#user: 'ada'});
  print('inside:  $r');
  // Intercept print inside the zone.
  final captured = <String>[];
  runZoned(() {
    print('hello');
    print('world');
  }, zoneSpecification: ZoneSpecification(print: (self, parent, zone, line) => captured.add(line)));
  print('captured prints: $captured');
}
Output
outside: user=nobody
inside:  user=ada
captured prints: [hello, world]
R? runZonedGuarded<R>(R body(), void onError(Object error, StackTrace stack), {Map<Object?, Object?>? zoneValues, ZoneSpecification? zoneSpecification})

Runs body in its own error zone.

Creates a new zone using Zone.fork based on zoneSpecification and zoneValues, then runs body in that zone and returns the result.

The onError function is used both to handle asynchronous errors by overriding ZoneSpecification.handleUncaughtError in zoneSpecification, if any, and to handle errors thrown synchronously by the call to body.

If an error occurs synchronously in body, then throwing in the onError handler makes the call to runZonedGuarded throw that error, and otherwise the call to runZonedGuarded returns null.

The created zone will always be an error zone. Asynchronous errors in futures never cross zone boundaries between zones with a different Zone.errorZone. A consequence of that behavior can be that a Future which completes as an error in the created zone will seem to never complete when used from a zone that belongs to a different error zone. Multiple attempts to use the future in a zone where the error is inaccessible will cause the error to be reported again in it's original error zone.

Example
import 'raya:async';

void main() {
  runZonedGuarded(() {
    Future(() => throw StateError('lost in a future'));
    print('zone body ran');
  }, (error, stack) {
    print('caught by the zone: $error');
  });
}
Output
zone body ran
caught by the zone: Bad state: lost in a future

Typedefs

typedef ControllerCallback = void Function()

Type of a stream controller's onListen, onPause and onResume callbacks.

typedef ControllerCancelCallback = FutureOr<void> Function()

Type of stream controller onCancel callbacks.

typedef ZoneCallback<R> = R Function()

A no-argument function, like the argument to Zone.run.

typedef ZoneUnaryCallback<R, T> = R Function(T)

A one-argument function, like the argument to Zone.runUnary.

typedef ZoneBinaryCallback<R, T1, T2> = R Function(T1, T2)

A two-argument function, like the argument to Zone.runBinary.

typedef HandleUncaughtErrorHandler = void Function(Zone self, ZoneDelegate parent, Zone zone, Object error, StackTrace stackTrace)

The type of a custom Zone.handleUncaughtError implementation function.

A function used as ZoneSpecification.handleUncaughtError to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The error and stackTrace are the error and stack trace that was uncaught in zone.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

If the uncaught error handler throws, the error will be passed to parent.handleUncaughtError. If the thrown object is error, the throw is considered a re-throw and the original stackTrace is retained. This allows an asynchronous error to leave the error zone.

RunHandlertypedef
typedef RunHandler = R Function<R>(Zone self, ZoneDelegate parent, Zone zone, R Function() f)

The type of a custom Zone.run implementation function.

A function used as ZoneSpecification.run to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f is the function which was passed to the Zone.run of zone.

The default behavior of Zone.run is to call f in the current zone, zone. A custom handler can do things before, after or instead of calling f.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef RunUnaryHandler = R Function<R, T>(Zone self, ZoneDelegate parent, Zone zone, R Function(T arg) f, T arg)

The type of a custom Zone.runUnary implementation function.

A function used as ZoneSpecification.runUnary to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f and value arg are the function and argument which was passed to the Zone.runUnary of zone.

The default behavior of Zone.runUnary is to call f with argument arg in the current zone, zone. A custom handler can do things before, after or instead of calling f.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef RunBinaryHandler = R Function<R, T1, T2>(Zone self, ZoneDelegate parent, Zone zone, R Function(T1 arg1, T2 arg2) f, T1 arg1, T2 arg2)

The type of a custom Zone.runBinary implementation function.

A function used as ZoneSpecification.runBinary to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f and values arg1 and arg2 are the function and arguments which was passed to the Zone.runBinary of zone.

The default behavior of Zone.runUnary is to call f with arguments arg1 and arg2 in the current zone, zone. A custom handler can do things before, after or instead of calling f.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef RegisterCallbackHandler = ZoneCallback<R> Function<R>(Zone self, ZoneDelegate parent, Zone zone, R Function() f)

The type of a custom Zone.registerCallback implementation function.

A function used as ZoneSpecification.registerCallback to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f is the function which was passed to the Zone.registerCallback of zone.

The handler should return either the function f or another function replacing f, typically by wrapping f in a function which does something extra before and after invoking f

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef RegisterUnaryCallbackHandler = ZoneUnaryCallback<R, T> Function<R, T>(Zone self, ZoneDelegate parent, Zone zone, R Function(T arg) f)

The type of a custom Zone.registerUnaryCallback implementation function.

A function used as ZoneSpecification.registerUnaryCallback to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f is the function which was passed to the which was passed to the Zone.registerUnaryCallback of zone.

The handler should return either the function f or another function replacing f, typically by wrapping f in a function which does something extra before and after invoking f

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef RegisterBinaryCallbackHandler = ZoneBinaryCallback<R, T1, T2> Function<R, T1, T2>(Zone self, ZoneDelegate parent, Zone zone, R Function(T1 arg1, T2 arg2) f)

The type of a custom Zone.registerBinaryCallback implementation function.

A function used as ZoneSpecification.registerBinaryCallback to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f is the function which was passed to the which was passed to the Zone.registerBinaryCallback of zone.

The handler should return either the function f or another function replacing f, typically by wrapping f in a function which does something extra before and after invoking f

typedef ErrorCallbackHandler = AsyncError? Function(Zone self, ZoneDelegate parent, Zone zone, Object error, StackTrace? stackTrace)

The type of a custom Zone.errorCallback implementation function.

A function used as ZoneSpecification.errorCallback to specialize the behavior of a new zone.

The error and stackTrace are the error and stack trace passed to Zone.errorCallback of zone.

The function will be called when a synchronous error becomes an asynchronous error, either by being caught, for example by a Future.then callback throwing, or when used to create an asynchronous error programmatically, for example using Future.error or Completer.complete.

If the function does not want to replace the error or stack trace, it should just return parent.errorCallback(zone, error, stackTrace), giving the parent zone the chance to intercept.

If the function does want to replace the error and/or stack trace, say with error2 and stackTrace2, it should still allow the parent zone to intercept those errors, for examples as:

return parent.errorCallback(zone, error, stackTrace) ??
    AsyncError(error, stackTrace);

The function returns either null if the original error and stack trace is unchanged, avoiding any allocation in the most common case, or an AsyncError containing a replacement error and stack trace which will be used in place of the originals as the asynchronous error.

The self Zone is the zone the handler was registered on, the parent delegate forwards to the handlers of self's parent zone, and zone is the current zone where the error was uncaught, which will have self as an ancestor zone.

The error callback handler must not throw.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef ScheduleMicrotaskHandler = void Function(Zone self, ZoneDelegate parent, Zone zone, void Function() f)

The type of a custom Zone.scheduleMicrotask implementation function.

A function used as ZoneSpecification.scheduleMicrotask to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The function f is the function which was passed to Zone.scheduleMicrotask of zone.

The custom handler can choose to replace the function f with one that does something before, after or instead of calling f, and then call parent.scheduleMicrotask(zone, replacement). Or it can implement its own microtask scheduling queue, which typically still depends on parent.scheduleMicrotask to as a way to get started.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef CreateTimerHandler = Timer Function(Zone self, ZoneDelegate parent, Zone zone, Duration duration, void Function() f)

The type of a custom Zone.createTimer implementation function.

A function used as ZoneSpecification.createTimer to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The callback function f and duration are the ones which were passed to Zone.createTimer of zone (possibly through the Timer constructor).

The custom handler can choose to replace the function f with one that does something before, after or instead of calling f, and then call parent.createTimer(zone, replacement). Or it can implement its own timer queue, which typically still depends on parent.createTimer to as a way to get started.

The function should return a Timer object which can be used to inspect and control the scheduled timer callback.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef CreatePeriodicTimerHandler = Timer Function(Zone self, ZoneDelegate parent, Zone zone, Duration period, void Function(Timer timer) f)

The type of a custom Zone.createPeriodicTimer implementation function.

A function used as ZoneSpecification.createPeriodicTimer to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The callback function f and period are the ones which were passed to Zone.createPeriodicTimer of zone (possibly through the Timer.periodic constructor).

The custom handler can choose to replace the function f with one that does something before, after or instead of calling f, and then call parent.createTimer(zone, replacement). Or it can implement its own timer queue, which typically still depends on parent.createTimer to as a way to get started.

The function should return a Timer object which can be used to inspect and control the scheduled timer callbacks.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef PrintHandler = void Function(Zone self, ZoneDelegate parent, Zone zone, String line)

The type of a custom Zone.print implementation function.

A function used as ZoneSpecification.print to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The string line is the one which was passed to Zone.print of zone, (possibly through the global print function).

The custom handler can intercept print operations and redirect them to other targets than the console.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

typedef ForkHandler = Zone Function(Zone self, ZoneDelegate parent, Zone zone, ZoneSpecification? specification, Map<Object?, Object?>? zoneValues)

The type of a custom Zone.fork implementation function.

A function used as ZoneSpecification.fork to specialize the behavior of a new zone.

Receives the Zone that the handler was registered on as self, a delegate forwarding to the handlers of self's parent zone as parent, and the current zone where the error was uncaught as zone, which will have self as a parent zone.

The handler should create a new zone with zone as its immediate parent zone.

The specification and zoneValues are the ones which were passed to Zone.fork of zone. They specify the custom zone handlers and zone variables that the new zone should have.

The custom handler can change the specification or zone values before calling parent.fork(zone, specification, zoneValues), but it has to call the parent's ZoneDelegate.fork in order to create a valid Zone object.

The function must only access zone-related functionality through self, parent or zone. It should not depend on the current zone (Zone.current).

Classes

final class AsyncError implements Error

An error and a stack trace.

Used when an error and stack trace need to be handled as a single value, for example when returned by Zone.errorCallback.

Example
import 'raya:async';

void main() {
  final e = AsyncError(StateError('disk full'), StackTrace.empty);
  print('error: ${e.error}');
  print('has stack: ${e.stackTrace == StackTrace.empty}');
  print('toString: $e');
}
Output
error: Bad state: disk full
has stack: true
toString: Bad state: disk full

Constructors

AsyncErrorconstructor
AsyncError(Object error, StackTrace? stackTrace)
Example
import 'raya:async';

void main() {
  final e = AsyncError(StateError('disk full'), StackTrace.empty);
  print('error: ${e.error}');
  print('has stack: ${e.stackTrace == StackTrace.empty}');
  print('toString: $e');
}
Output
error: Bad state: disk full
has stack: true
toString: Bad state: disk full

Static

defaultStackTracestaticmethod
static StackTrace defaultStackTrace(Object error)

A default stack trace for an error.

If error is an Error and it has an Error.stackTrace, that stack trace is returned. If not, the StackTrace.empty default stack trace is returned.

Example
import 'raya:async';

void main() {
  final err = ArgumentError('bad');
  final st = AsyncError.defaultStackTrace(err);
  print('is StackTrace: ${st is StackTrace}');
  final e = AsyncError(err, null); // null stack falls back to the default
  print('error: ${e.error}');
  print('stack is StackTrace: ${e.stackTrace is StackTrace}');
}
Output
is StackTrace: true
error: Invalid argument(s): bad
stack is StackTrace: true

Properties

errorfield
final Object error
final StackTrace stackTrace

Methods

toStringmethod
String toString()
Example
import 'raya:async';

void main() {
  print(AsyncError('plain string error', StackTrace.empty).toString());
  print(AsyncError(FormatException('not a number', 'x1'), StackTrace.empty).toString());
}
Output
plain string error
FormatException: not a number
x1
final class DeferredLoadException implements Exception

Thrown when a deferred library fails to load.

Example
import 'raya:async';

void main() {
  final e = DeferredLoadException('library "charts" failed to load');
  print('is Exception: ${e is Exception}');
  print('message: $e');
  try {
    throw e;
  } on DeferredLoadException catch (x) {
    print('caught: $x');
  }
}
Output
is Exception: true
message: DeferredLoadException: 'library "charts" failed to load'
caught: DeferredLoadException: 'library "charts" failed to load'

Constructors

DeferredLoadException(String message)
Example
import 'raya:async';

void main() {
  final e = DeferredLoadException('library "charts" failed to load');
  print('is Exception: ${e is Exception}');
  print('message: $e');
  try {
    throw e;
  } on DeferredLoadException catch (x) {
    print('caught: $x');
  }
}
Output
is Exception: true
message: DeferredLoadException: 'library "charts" failed to load'
caught: DeferredLoadException: 'library "charts" failed to load'

Methods

toStringmethod
String toString()
Example
import 'raya:async';

void main() {
  print(DeferredLoadException('timeout').toString());
  print(DeferredLoadException('').toString().length);
}
Output
DeferredLoadException: 'timeout'
25
abstract class FutureOr<T>

A type representing values that are either Future<T> or T.

This class declaration is a public stand-in for an internal future-or-value generic type, which is not a class type. References to this class are resolved to the internal type.

It is a compile-time error for any class to extend, mix in or implement FutureOr.

Examples
// The `Future<T>.then` function takes a callback [f] that returns either
// an `S` or a `Future<S>`.
Future<S> then<S>(FutureOr<S> f(T x), ...);

// `Completer<T>.complete` takes either a `T` or `Future<T>`.
void complete(FutureOr<T> value);
Advanced

The FutureOr<int> type is actually the "type union" of the types int and Future<int>. This type union is defined in such a way that FutureOr<Object> is both a super- and sub-type of Object (sub-type because Object is one of the types of the union, super-type because Object is a super-type of both of the types of the union). Together it means that FutureOr<Object> is equivalent to Object.

As a corollary, FutureOr<Object> is equivalent to FutureOr<FutureOr<Object>>, FutureOr<Future<Object>> is equivalent to Future<Object>.

Example
import 'raya:async';

// A FutureOr<int> may be an int or a Future<int>; await handles both.
FutureOr<int> lookup(String key) => key == 'cached' ? 1 : Future.value(2);

Future<void> main() async {
  final a = lookup('cached');
  final b = lookup('remote');
  print('a is int: ${a is int}, b is Future: ${b is Future}');
  print('a = ${await a}, b = ${await b}');
}
Output
a is int: true, b is Future: true
a = 1, b = 2
class

Future

abstract interface class Future<T>

The result of an asynchronous computation.

An asynchronous computation cannot provide a result immediately when it is started, unlike a synchronous computation which does compute a result immediately by either returning a value or by throwing. An asynchronous computation may need to wait for something external to the program (reading a file, querying a database, fetching a web page) which takes time. Instead of blocking all computation until the result is available, the asynchronous computation immediately returns a Future which will eventually "complete" with the result.

Asynchronous programming

To perform an asynchronous computation, you use an async function which always produces a future. Inside such an asynchronous function, you can use the await operation to delay execution until another asynchronous computation has a result. While execution of the awaiting function is delayed, the program is not blocked, and can continue doing other things.

Example:

import "raya:io";
Future<bool> fileContains(String path, String needle) async {
   var haystack = await File(path).readAsString();
   return haystack.contains(needle);
}

Here the File.readAsString method from raya:io is an asynchronous function returning a Future<String>. The fileContains function is marked with async right before its body, which means that you can use await inside it, and that it must return a future. The call to File(path).readAsString initiates reading the file into a string and produces a Future<String> which will eventually contain the result. The await then waits for that future to complete with a string (or an error, if reading the file fails). While waiting, the program can do other things. When the future completes with a string, the fileContains function computes a boolean and returns it, which then completes the original future that it returned when first called.

If a future completes with an error, awaiting that future will (re-)throw that error. In the example here, we can add error checking:

import "raya:io";
Future<bool> fileContains(String path, String needle) async {
  try {
    var haystack = await File(path).readAsString();
    return haystack.contains(needle);
  } on FileSystemException catch (exception, stack) {
    _myLog.logError(exception, stack);
    return false;
  }
}

You use a normal try/catch to catch the failures of awaited asynchronous computations.

In general, when writing asynchronous code, you should always await a future when it is produced, and not wait until after another asynchronous delay. That ensures that you are ready to receive any error that the future might produce, which is important because an asynchronous error that no-one is awaiting is an uncaught error and may terminate the running program.

Programming with the Future API.

The Future class also provides a more direct, low-level functionality for accessing the result that it completes with. The async and await language features are built on top of this functionality, and it sometimes makes sense to use it directly. There are things that you cannot do by just awaiting one future at a time.

With a Future, you can manually 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));

Since a Future can be completed in two ways, either with a value (if the asynchronous computation succeeded) or with an error (if the computation failed), you can install callbacks for either or both cases.

In some cases we say that a future is completed with another future. This is a short way of stating that the future is completed in the same way, with the same value or error, as the other future once that other future itself completes. Most functions in the platform libraries that complete a future (for example Completer.complete or Future.value), also accepts another future, and automatically handles forwarding the result to the future being completed.

The result of registering callbacks is itself a Future, which in turn is completed with the result of invoking the corresponding callback with the original future's result. The new future 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 any registered handler when it completes with an error, it forwards the error to an "uncaught-error handler". This behavior ensures 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();
Timer(const Duration(milliseconds: 5), () {
  // The error-handler is not attached until 5 ms after the future has
  // been received. If the future fails before that, the error is
  // forwarded to the global error-handler, even though there is code
  // (just below) to eventually handle the error.
  future.then((value) { useValue(value); },
              onError: (e) { handleError(e); });
});

When registering callbacks, it's often more readable to register the two callbacks separately, by first using then with one argument (the value handler) and using a second catchError for handling errors. Each of these will forward the result that they don't handle to their successors, and together they handle both value and error result. It has the additional benefit of the catchError handling errors in the then value callback too. Using sequential handlers instead of parallel ones often leads to code that is easier to reason about. It also 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> asyncValue = Future(foo);  // Result of foo() as a future.
asyncValue.then((int value) {
  return bar(value);
}).catchError((e) {
  return 499;
});

Similar to the synchronous code, the error handler (registered with catchError) is handling any errors thrown by either foo or bar. If the error-handler had been registered as the onError parameter of the then call, it would not catch errors from the bar call.

Futures can have more than one callback-pair registered. Each successor is treated independently and is handled as if it was the only successor. The order in which the individual successors are completed is undefined.

A future may also fail to ever complete. In that case, no callbacks are called. That situation should generally be avoided if possible, unless it's very clearly documented.

Example
import 'raya:async';

Future<String> fetchName(int id) async {
  await Future<void>.delayed(Duration.zero);
  return 'user$id';
}

Future<void> main() async {
  print('start');
  final name = await fetchName(7);
  print('got $name');
  final names = await Future.wait([for (var i = 1; i <= 3; i++) fetchName(i)]);
  print('all: $names');
}
Output
start
got user7
all: [user1, user2, user3]

Constructors

Futurefactory
factory Future(FutureOr<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 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 non-future value is returned, the returned future is completed with that value.

Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  final f = Future(() {
    order.add('computation');
    return 6 * 7;
  });
  order.add('after Future()');
  print('value: ${await f}');
  print('order: $order'); // the computation runs later, on a timer
  final g = Future<int>(() => Future.value(5)); // may return a future too
  print('nested: ${await g}');
}
Output
value: 42
order: [after Future(), computation]
nested: 5
factory Future.microtask(FutureOr<T> computation())

Creates a future containing the result of calling computation asynchronously with scheduleMicrotask.

If executing computation throws, the returned future is completed with the thrown error.

If calling computation returns a Future, completion of the created future will wait until the returned future completes, and will then complete with the same result.

If calling computation returns a non-future value, the returned future is completed with that value.

Example
import 'raya:async';

void main() {
  Future(() => print('3. a Future (event queue)'));
  Future.microtask(() => print('2. a microtask'));
  scheduleMicrotask(() => print('2b. another microtask'));
  print('1. synchronous code');
}
Output
1. synchronous code
2. a microtask
2b. another microtask
3. a Future (event queue)
factory Future.sync(FutureOr<T> computation())

The result of calling computation as a future.

Mainly used when working with functions returning a FutureOr<T>, or non-async functions in a non-async asynchronous function, where you want to capture any error in a future.

If calling computation throws, the returned future is completed with the error.

If calling computation returns a Future<T>, that future is returned.

If calling computation returns a non-Future<T> value, a future is created which has been completed with that value.

Example:

Future<int> asyncAdd(
  FutureOr<int> Function() a,
  FutureOr<int> Function() b,
) =>
  (Future.sync(a), Future.sync(b)).wait.then((ab) => ab.$1 + ab.$2);

To create a future with a known value, use Future.syncValue instead, as Future.syncValue(12).

Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  final f = Future.sync(() {
    order.add('computation');
    return 10;
  });
  order.add('after Future.sync');
  print('order: $order'); // ran immediately
  print('value: ${await f}');
  final bad = Future<int>.sync(() => throw StateError('boom'));
  print('error captured: ${await bad.catchError((Object e) => -1)}');
}
Output
order: [computation, after Future.sync]
value: 10
error captured: -1
factory Future.syncValue(T value)

Creates a future completed with value.

The future is guaranteed to not have an error.

If a synchronous computation can throw, rather than doing Future.syncValue(computation) and wrapping that in a try/catch, you can use Future.sync which catches an error into its returned future, as Future.sync( => computation).

Example
import 'raya:async';

Future<void> main() async {
  final f = Future.syncValue(42);
  print('is Future<int>: ${f is Future<int>}');
  print('value: ${await f}');
  final names = await Future.syncValue(['a', 'b']);
  print('list: $names');
}
Output
is Future<int>: true
value: 42
list: [a, b]
factory Future.value([FutureOr<T>? value])

Creates a future completed with value.

If value is a future, the created future waits for the value future to complete, and then completes with the same result. Since a value future can complete with an error, so can the future created by Future.value, even if the name suggests otherwise.

If value is not a Future, the created future is completed with the value value, equivalently to new Future<T>.sync( => value).

If value is omitted or null, it is converted to FutureOr<T> by value as FutureOr<T>. If T is not nullable, then a non-null value must be provided, otherwise the construction throws.

Use Completer to create a future now and complete it later.

Example:

Future<int> getFuture() {
 return Future<int>.value(2021);
}

final result = await getFuture();
Example
import 'raya:async';

Future<int> cachedOrFetch(Map<String, int> cache, String k) =>
    cache.containsKey(k) ? Future.value(cache[k]) : Future.delayed(Duration.zero, () => 99);

Future<void> main() async {
  print('value: ${await Future.value(3)}');
  final done = Future<void>.value();
  await done;
  print('Future<void>.value() completes: true');
  print('cached: ${await cachedOrFetch({'x': 1}, 'x')}');
  print('fetched: ${await cachedOrFetch({}, 'y')}');
}
Output
value: 3
Future<void>.value() completes: true
cached: 1
fetched: 99
factory Future.error(Object error, [StackTrace? stackTrace])

Creates a future that completes with an error.

The created future will be completed with an error in a future microtask. This allows enough time for someone to add an error handler on the future. If an error handler isn't added before the future completes, the error will be considered unhandled.

Use Completer to create a future and complete it later.

Example:

Future<int> getFuture() {
 return Future.error(Exception('Issue'));
}

final error = await getFuture(); // Throws.
Example
import 'raya:async';

Future<int> parsePort(String s) {
  final n = int.tryParse(s);
  return n == null ? Future.error(FormatException('bad port', s)) : Future.value(n);
}

Future<void> main() async {
  print('ok: ${await parsePort('8080')}');
  try {
    await parsePort('http');
  } on FormatException catch (e) {
    print('error: ${e.message} (${e.source})');
  }
}
Output
ok: 8080
error: bad port (http)
factory Future.delayed(Duration duration, [FutureOr<T> Function()? computation])

Creates a future that runs its computation after a delay.

The computation will be executed after the given duration has passed, and the future is completed with the result of the computation.

If computation returns a future, the future returned by this constructor will complete with the value or error of that future, which may not be available until even later.

If the duration is 0 or less, it completes no sooner than in the next event-loop iteration, after all microtasks have run. (The waiting for the delay uses a Timer created in the current zone.)

The computation must not be omitted, and must not be null. Use Future.pause instead if you just want to wait for duration. Until that is reflected in the signature, if computation is omitted, then T must be nullable. Then the computation will be treated as if it was => null, and the future will eventually complete with the null value.

If calling computation throws, the created future will complete with the error.

See also Completer for a way to create and complete a future at a later time that isn't necessarily after a known fixed duration.

Example:

var now = DateTime.now();
var later = await Future.delayed(const Duration(seconds: 1), () {
  return DateTime.timestamp();
});
print(now.difference(later)); // At least a second.
Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  final slow = Future.delayed(const Duration(milliseconds: 20), () => order.add('slow'));
  final fast = Future.delayed(const Duration(milliseconds: 5), () => order.add('fast'));
  await Future.wait([slow, fast]);
  print('finished in this order: $order');
}
Output
finished in this order: [fast, slow]

Static

pausestaticmethod
static Future<void> pause([Duration duration = Duration.zero])

Creates a Future that completes with no result after duration.

Like Future.delayed, but does not perform any action, and cannot complete with an error.

Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  scheduleMicrotask(() => order.add('microtask'));
  order.add('before pause');
  await Future.pause(); // yields to the event loop
  order.add('after pause');
  print('order: $order');
}
Output
order: [before pause, microtask, after pause]
waitstaticmethod
static Future<List<T>> wait<T>(Iterable<Future<T>> futures, {bool eagerError = false, void cleanUp(T successValue)?})

Waits for multiple futures to complete and collects their results.

Returns a future which will complete once all the provided futures have completed, either with their results, or with an error if any of the provided futures fail.

The value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures.

If any future completes with an error, then the returned future completes with that error. If further futures also complete with errors, those errors are discarded.

If eagerError is true, the returned future completes with an error immediately on the first error from one of the futures. Otherwise all futures must complete before the returned future is completed (still with the first error; the remaining errors are silently dropped).

In the case of an error, cleanUp (if provided), is invoked on any non-null result of successful futures. This makes it possible to cleanUp resources that would otherwise be lost (since the returned future does not provide access to these values). The cleanUp function is unused if there is no error.

The call to cleanUp should not throw. If it does, the error will be an uncaught asynchronous error.

Example:

void main() async {
  var value = await Future.wait([delayedNumber(), delayedString()]);
  print(value); // [2, result]
}

Future<int> delayedNumber() async {
  await Future.delayed(const Duration(seconds: 2));
  return 2;
}

Future<String> delayedString() async {
  await Future.delayed(const Duration(seconds: 2));
  return 'result';
}
Example
import 'raya:async';

Future<int> square(int x) async => x * x;

Future<void> main() async {
  final results = await Future.wait([square(2), square(3), square(4)]);
  print('results in order: $results');
  final sum = results.fold<int>(0, (a, b) => a + b);
  print('sum: $sum');
}
Output
results in order: [4, 9, 16]
sum: 29
anystaticmethod
static Future<T> any<T>(Iterable<Future<T>> futures)

Returns the result of the first future in futures to complete.

The returned future is completed with the result of the first future in futures to report that it is complete, whether it's with a value or an error. The results of all the other futures are discarded.

If futures is empty, or if none of its futures complete, the returned future never completes.

Example:

void main() async {
  final result =
      await Future.any([slowInt(), delayedString(), fastInt()]);
  // The future of fastInt completes first, others are ignored.
  print(result); // 3
}
Future<int> slowInt() async {
  await Future.delayed(const Duration(seconds: 2));
  return 2;
}

Future<String> delayedString() async {
  await Future.delayed(const Duration(seconds: 2));
  throw TimeoutException('Time has passed');
}

Future<int> fastInt() async {
  await Future.delayed(const Duration(seconds: 1));
  return 3;
}
Example
import 'raya:async';

Future<void> main() async {
  final first = await Future.any([
    Future.delayed(const Duration(milliseconds: 30), () => 'slow mirror'),
    Future.delayed(const Duration(milliseconds: 1), () => 'fast mirror'),
  ]);
  print('first: $first');
  // An error that completes first wins too.
  final r = await Future.any<String>([
    Future.error('offline'),
    Future.delayed(const Duration(milliseconds: 20), () => 'late'),
  ]).catchError((Object e) => 'error: $e');
  print(r);
}
Output
first: fast mirror
error: offline
forEachstaticmethod
static Future<void> forEach<T>(Iterable<T> elements, FutureOr action(T element))

Performs an action for each element of the iterable, in turn.

The action may be either synchronous or asynchronous.

Calls action with each element in elements in order. If the call to action returns a Future<T>, the iteration waits until the future is completed before continuing with the next element.

Returns a Future that completes with null when all elements have been processed.

Non-Future return values, and completion-values of returned Futures, are discarded.

Any error from action, synchronous or asynchronous, will stop the iteration and be reported in the returned Future.

Example
import 'raya:async';

Future<String> fetch(String id) async => 'item-$id';

Future<void> main() async {
  final got = <String>[];
  // Runs one action at a time, in order, awaiting each.
  await Future.forEach(['a', 'b', 'c'], (String id) async {
    got.add(await fetch(id));
  });
  print('sequential: $got');
  var sum = 0;
  await Future.forEach([1, 2, 3], (int n) => sum += n); // sync actions are fine
  print('sum: $sum');
}
Output
sequential: [item-a, item-b, item-c]
sum: 6
doWhilestaticmethod
static Future<void> doWhile(FutureOr<bool> action())

Performs an operation repeatedly until it returns false.

The operation, action, may be either synchronous or asynchronous.

The operation is called repeatedly as long as it returns either the bool value true or a Future<bool> which completes with the value true.

If a call to action returns false or a Future that completes to false, iteration ends and the future returned by doWhile is completed with a null value.

If a call to action throws or a future returned by action completes with an error, iteration ends and the future returned by doWhile completes with the same error.

Calls to action may happen at any time, including immediately after calling doWhile. The only restriction is a new call to action won't happen before the previous call has returned, and if it returned a Future<bool>, not until that future has completed.

Example:

void main() async {
  var value = 0;
  await Future.doWhile(() async {
    value++;
    await Future.delayed(const Duration(seconds: 1));
    if (value == 3) {
      print('Finished with $value');
      return false;
    }
    return true;
  });
}
// Outputs: 'Finished with 3'
Example
import 'raya:async';

Future<void> main() async {
  var attempt = 0;
  // Retry until the action returns false.
  await Future.doWhile(() async {
    attempt++;
    print('attempt $attempt');
    return attempt < 3;
  });
  print('done after $attempt attempts');
}
Output
attempt 1
attempt 2
attempt 3
done after 3 attempts

Methods

thenmethod
Future<R> then<R>(FutureOr<R> onValue(T value), {Function? onError})

Register callbacks to be called when this future completes.

When this future completes with a value, the onValue callback will be called with that value. If this future is already completed, the callback will not be called immediately, but will be scheduled in a later microtask.

If onError is provided, and this future completes with an error, the onError callback is called with that error and its stack trace. The onError callback must accept either one argument or two arguments where the latter is a StackTrace. If onError accepts two arguments, it is called with both the error and the stack trace, otherwise it is called with just the error object. The onError callback must return a value or future that can be used to complete the returned future, so it must be something assignable to FutureOr<R>.

Returns a new Future which is completed with the result of the call to onValue (if this future completes with a value) or to onError (if this future completes with an error).

If the invoked callback throws, the returned future is completed with the thrown error and a stack trace for the error. In the case of onError, if the exception thrown is identical to the error argument to onError, and it is thrown synchronously the throw is considered a rethrow, and the original stack trace is used instead. To rethrow with the same stack trace in an asynchronous callback, use Error.throwWithStackTrace.

If the callback returns a Future, the future returned by then will be completed with the same result as the future returned by the callback.

If onError is not given, and this future completes with an error, the error is forwarded directly to the returned future.

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.

Note that futures don't delay reporting of errors until listeners are added. If the first then or catchError call happens after this future has completed with an error, then the error is reported as unhandled error. See the description on Future.

Example
import 'raya:async';

void main() {
  Future.value(21)
      .then((x) => x * 2)
      .then((x) => print('then: $x'))
      .whenComplete(() => print('whenComplete runs last'));
  print('this line prints first: futures run later');
}
Output
this line prints first: futures run later
then: 42
whenComplete runs last
Future<T> catchError(Function onError, {bool test(Object error)?})

Handles errors emitted by this Future.

This is the asynchronous equivalent of a "catch" block.

Returns a new Future that will be completed with either the result of this future or the result of calling the onError callback.

If this future completes with a value, the returned future completes with the same value.

If this future completes with an error, then test is first called with the error value.

If test returns false, the exception is not handled by this catchError, and the returned future completes with the same error and stack trace as this future.

If test returns true, onError is called with the error and possibly stack trace, and the returned future is completed with the result of this call in exactly the same way as for then's onError.

If test is omitted, it defaults to a function that always returns true. The test function should not throw, but if it does, it is handled as if the onError function had thrown.

Note that futures don't delay reporting of errors until listeners are added. If the first catchError (or then) call happens after this future has completed with an error then the error is reported as unhandled error. See the description on Future.

Example:

Future.delayed(
  const Duration(seconds: 1),
  () => throw 401,
).then((value) {
  throw 'Unreachable';
}).catchError((err) {
  print('Error: $err'); // Prints 401.
}, test: (error) {
  return error is int && error >= 400;
});
Example
import 'raya:async';

Future<int> parse(String s) async => int.parse(s);

Future<void> main() async {
  final ok = await parse('12').catchError((_) => -1);
  final bad = await parse('twelve').catchError((Object e) => -1);
  print('ok: $ok, bad: $bad');
  try {
    await parse('x');
  } on FormatException catch (e) {
    print('try/catch with await: ${e.message}');
  }
}
Output
ok: 12, bad: -1
try/catch with await: Invalid radix-10 number
Future<T> whenComplete(FutureOr<void> action())

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

Example:

void main() async {
  var value =
      await waitTask().whenComplete(() => print('do something here'));
  // Prints "do something here" after waitTask() completed.
  print(value); // Prints "done"
}

Future<String> waitTask() {
  Future.delayed(const Duration(seconds: 5));
  return Future.value('done');
}
// Outputs: 'do some work here' after waitTask is completed.
Example
import 'raya:async';

Future<int> work(bool fail) async => fail ? throw StateError('failed') : 7;

Future<void> main() async {
  final ok = await work(false).whenComplete(() => print('cleanup 1'));
  print('ok: $ok');
  try {
    await work(true).whenComplete(() => print('cleanup 2 (runs on error too)'));
  } on StateError catch (e) {
    print('error still propagates: ${e.message}');
  }
}
Output
cleanup 1
ok: 7
cleanup 2 (runs on error too)
error still propagates: failed
asStreammethod
Stream<T> asStream()

Creates a Stream containing the result of this future.

The stream will produce single data or error event containing the completion result of this future, and then it will close with a done event.

If the future never completes, the stream will not produce any events.

Example
import 'raya:async';

Future<void> main() async {
  final s = Future.value('only event').asStream();
  await for (final e in s) {
    print('event: $e');
  }
  final events = await Future.value(5).asStream().map((n) => n * 2).toList();
  print('mapped: $events');
}
Output
event: only event
mapped: [10]
timeoutmethod
Future<T> timeout(Duration timeLimit, {FutureOr<T> onTimeout()?})

Stop waiting for this future after timeLimit has passed.

Creates a new timeout future that completes with the same result as this future, the source future, if the source future completes in time.

If the source future does not complete before timeLimit has passed, the onTimeout action is executed, and its result (whether it returns or throws) is used as the result of the timeout future. The onTimeout function must return a T or a Future<T>. If onTimeout returns a future, the alternative result future, the eventual result of the alternative result future is used to complete the timeout future, even if the source future completes before the alternative result future. It only matters that the source future did not complete in time.

If onTimeout is omitted, a timeout will cause the returned future to complete with a TimeoutException.

In either case, the source future can still complete normally at a later time. It just won't be used as the result of the timeout future unless it completes within the time bound. Even if the source future completes with an error, if that error happens after timeLimit has passed, the error is ignored, just like a value result would be.

Examples:

void main() async {
  var result =
      await waitTask("completed").timeout(const Duration(seconds: 10));
  print(result); // Prints "completed" after 5 seconds.

  result = await waitTask("completed")
      .timeout(const Duration(seconds: 1), onTimeout: () => "timeout");
  print(result); // Prints "timeout" after 1 second.

  result = await waitTask("first").timeout(const Duration(seconds: 2),
      onTimeout: () => waitTask("second"));
  print(result); // Prints "second" after 7 seconds.

  try {
    await waitTask("completed").timeout(const Duration(seconds: 2));
  } on TimeoutException {
    print("throws"); // Prints "throws" after 2 seconds.
  }

  var printFuture = waitPrint();
  await printFuture.timeout(const Duration(seconds: 2), onTimeout: () {
    print("timeout"); // Prints "timeout" after 2 seconds.
  });
  await printFuture; // Prints "printed" after additional 3 seconds.

  try {
    await waitThrow("error").timeout(const Duration(seconds: 2));
  } on TimeoutException {
    print("throws"); // Prints "throws" after 2 seconds.
  }
  // StateError is ignored
}

/// Returns [string] after five seconds.
Future<String> waitTask(String string) async {
  await Future.delayed(const Duration(seconds: 5));
  return string;
}

/// Prints "printed" after five seconds.
Future<void> waitPrint() async {
  await Future.delayed(const Duration(seconds: 5));
  print("printed");
}
/// Throws a [StateError] with [message] after five seconds.
Future<void> waitThrow(String message) async {
  await Future.delayed(const Duration(seconds: 5));
  throw Exception(message);
}
Example
import 'raya:async';

Future<void> main() async {
  final slow = Future.delayed(const Duration(milliseconds: 200), () => 'slow result');
  final r = await slow.timeout(const Duration(milliseconds: 10), onTimeout: () => 'timed out');
  print(r);
  try {
    await Completer<void>().future.timeout(const Duration(milliseconds: 5));
  } on TimeoutException {
    print('TimeoutException caught');
  }
}
Output
timed out
TimeoutException caught
extension FutureExtensions<T> on Future<T>

Convenience methods on futures.

Adds functionality to futures which makes it easier to write well-typed asynchronous code.

Example
import 'raya:async';

Future<int> risky(int n) async => n.isOdd ? throw ArgumentError('odd: $n') : n;

Future<void> main() async {
  final a = await risky(3).onError<ArgumentError>((e, st) => -1);
  print('onError recovered: $a');
  risky(5).ignore(); // drop the result and any error
  print('ignored an error without crashing');
}
Output
onError recovered: -1
ignored an error without crashing

Methods

onErrormethod
Future<T> onError<E extends Object>(FutureOr<T> handleError(E error, StackTrace stackTrace), {bool test(E error)?})

Handles errors on this future.

Catches errors of type E that this future complete with. If test is supplied, only catches errors of type E where test returns true. If E is Object, then all errors are potentially caught, depending only on a supplied test.

If the error is caught, the returned future completes with the result of calling handleError with the error and stack trace. This result must be a value of the same type that this future could otherwise complete with. For example, if this future cannot complete with null, then handleError also cannot return null. Example:

Future<T> retryOperation<T>(Future<T> operation(), T onFailure()) =>
    operation().onError<RetryException>((e, s) {
      if (e.canRetry) {
        return retryOperation(operation, onFailure);
      }
      return onFailure();
    });

If handleError throws, the returned future completes with the thrown error and stack trace, except that if it throws the same error object again, then it is considered a "rethrow" and the original stack trace is retained. This can be used as an alternative to skipping the error in test. Example:

// Unwraps an exceptions cause, if it has one.
someFuture.onError<SomeException>((e, _) {
  throw e.cause ?? e;
});
// vs.
someFuture.onError<SomeException>((e, _) {
  throw e.cause!;
}, test: (e) => e.cause != null);

If the error is not caught, the returned future completes with the same result, value or error, as this future.

This method is effectively a more precisely typed version of Future.catchError. It makes it easy to catch specific error types, and requires a correctly typed error handler function, rather than just Function. Because of this, the error handlers must accept the stack trace argument.

Example
import 'raya:async';

Future<int> load(String s) async => int.parse(s);

Future<void> main() async {
  final a = await load('12').onError((Object e, st) => -1);
  final b = await load('x').onError<FormatException>((e, st) => -1);
  print('a = $a, b = $b');
  // test: only handle some errors of the type.
  final c = await load('').onError<FormatException>((e, st) => 0, test: (e) => e.source == '');
  print('empty string handled: $c');
}
Output
a = 12, b = -1
empty string handled: 0
ignoremethod
void ignore()

Completely ignores this future and its result.

Not all futures are important, not even if they contain errors, for example if a request was made, but the response is no longer needed. Simply ignoring a future can result in uncaught asynchronous errors. This method instead handles (and ignores) any values or errors coming from this future, making it safe to otherwise ignore the future.

Use ignore to signal that the result of the future is no longer important to the program, not even if it's an error. That will ensure that an unexpected error is still reported.

Example
import 'raya:async';

Future<void> main() async {
  var ran = false;
  Future(() {
    ran = true;
    throw StateError('nobody listens');
  }).ignore(); // the error is not reported as uncaught
  await Future.delayed(const Duration(milliseconds: 1));
  print('computation ran: $ran');
  print('program still running');
}
Output
computation ran: true
program still running
class TimeoutException implements Exception

Thrown when a scheduled timeout happens while waiting for an async result.

Example
import 'raya:async';

Future<void> main() async {
  final e = TimeoutException('server slow', const Duration(seconds: 2));
  print('message: ${e.message}');
  print('duration: ${e.duration}');
  print('toString: $e');
  try {
    await Completer<int>().future.timeout(const Duration(milliseconds: 5));
  } on TimeoutException catch (t) {
    print('from timeout(): has duration ${t.duration != null}');
  }
}
Output
message: server slow
duration: 0:00:02.000000
toString: TimeoutException after 0:00:02.000000: server slow
from timeout(): has duration true

Constructors

TimeoutExceptionconstructor
TimeoutException(this.message, [this.duration])
Example
import 'raya:async';

Future<void> main() async {
  final e = TimeoutException('server slow', const Duration(seconds: 2));
  print('message: ${e.message}');
  print('duration: ${e.duration}');
  print('toString: $e');
  try {
    await Completer<int>().future.timeout(const Duration(milliseconds: 5));
  } on TimeoutException catch (t) {
    print('from timeout(): has duration ${t.duration != null}');
  }
}
Output
message: server slow
duration: 0:00:02.000000
toString: TimeoutException after 0:00:02.000000: server slow
from timeout(): has duration true

Properties

messagefield
final String? message

Description of the cause of the timeout.

final Duration? duration

The duration that was exceeded.

Methods

toStringmethod
String toString()
Example
import 'raya:async';

void main() {
  print(TimeoutException('no reply').toString());
  print(TimeoutException('no reply', const Duration(milliseconds: 1500)).toString());
  print(TimeoutException(null).toString());
}
Output
TimeoutException: no reply
TimeoutException after 0:00:01.500000: no reply
TimeoutException
abstract interface class Completer<T>

A way to produce Future objects and to complete them later with a value or error.

Most of the time, the simplest way to create a future is to just use one of the Future constructors to capture the result of a single asynchronous computation:

Future(() { doSomething(); return result; });

Or, if the future represents the result of a sequence of asynchronous computations, they can be chained using Future.then or similar functions on Future:

Future doStuff(){
  return someAsyncOperation().then((result) {
    return someOtherAsyncOperation(result);
  });
}

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 {
  final 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.
  void _finishOperation(T result) {
    _completer.complete(result);
  }

  // If something goes wrong, call this.
  void _errorHappened(error) {
    _completer.completeError(error);
  }
}
Example
import 'raya:async';

// Turn a callback API into a Future with a Completer.
void computeLater(int x, void Function(int) done) {
  Timer.run(() => done(x * 10));
}

Future<int> compute(int x) {
  final c = Completer<int>();
  computeLater(x, c.complete);
  return c.future;
}

Future<void> main() async {
  final c = Completer<String>();
  print('isCompleted: ${c.isCompleted}');
  c.complete('done');
  print('isCompleted: ${c.isCompleted}, value: ${await c.future}');
  print('compute(4) = ${await compute(4)}');
}
Output
isCompleted: false
isCompleted: true, value: done
compute(4) = 40

Constructors

Completerfactory
factory Completer()

Creates a new completer.

The general workflow for creating a new future is to 1) create a new completer, 2) hand out its future, and, at a later point, 3) invoke either complete or completeError.

The completer completes the future asynchronously. That means that callbacks registered on the future are not called immediately when complete or completeError is called. Instead the callbacks are delayed until a later microtask.

Example:

var completer = new Completer();
handOut(completer.future);
later: {
  completer.complete('completion value');
}
Example
import 'raya:async';

Future<void> main() async {
  final ready = Completer<String>();
  Timer.run(() => ready.complete('config loaded'));
  print('waiting... completed: ${ready.isCompleted}');
  print('got: ${await ready.future}');
  print('completed: ${ready.isCompleted}');
}
Output
waiting... completed: false
got: config loaded
completed: true
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.

Using an normal, asynchronous, completer will never give the wrong behavior, but using a synchronous completer incorrectly can cause otherwise correct programs to break.

A synchronous completer is only intended for optimizing event propagation when one asynchronous event immediately triggers another. It should not be used unless the calls to complete and completeError are guaranteed to occur in places where it won't break Future invariants.

Completing synchronously means that the completer's future will be completed immediately when calling the complete or completeError method on a synchronous completer, which also calls any callbacks registered on that future.

Completing synchronously must not break the rule that when you add a callback on a future, that callback must not be called until the code that added the callback has completed. For that reason, a synchronous completion must only occur at the very end (in "tail position") of another synchronous event, because at that point, completing the future immediately is be equivalent to returning to the event loop and completing the future in the next microtask.

Example:

var completer = 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 = 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().
});
Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  final c = Completer<int>.sync();
  c.future.then((v) => order.add('listener got $v'));
  c.complete(1);
  order.add('after complete');
  await Future.value();
  print('sync completer:  $order'); // listener ran inside complete()
  final order2 = <String>[];
  final d = Completer<int>();
  d.future.then((v) => order2.add('listener got $v'));
  d.complete(1);
  order2.add('after complete');
  await Future.value();
  print('async completer: $order2');
}
Output
sync completer:  [listener got 1, after complete]
async completer: [after complete, listener got 1]

Properties

futuregetter
Future<T> get future

The future that is completed by this completer.

The future that is completed when complete or completeError is called.

bool get isCompleted

Whether the future has been completed.

Reflects whether complete or completeError has been called. A true value doesn't necessarily mean that listeners of this future have been invoked yet, either because the completer usually waits until a later microtask to propagate the result, or because complete was called with a future that hasn't completed yet.

When this value is true, complete and completeError must not be called again.

Methods

completemethod
void complete([FutureOr<T>? value])

Completes future with the supplied values.

The value must be either a value of type T or a future of type Future<T>. If the value is omitted or null, and T is not nullable, the call to complete throws.

If the value is itself a future, the completer will wait for that future to complete, and complete with the same result, whether it is a success or an error.

Calling complete or completeError must be done at most once.

All listeners on the future are informed about the value.

Example
import 'raya:async';

Future<void> main() async {
  final c = Completer<int>();
  c.complete(Future.value(9)); // completing with a future chains it
  print('value: ${await c.future}');
  try {
    c.complete(10);
  } on StateError catch (e) {
    print('second complete: ${e.message}');
  }
  final v = Completer<void>()..complete();
  print('void completer done: ${v.isCompleted}');
}
Output
value: 9
second complete: Future already completed
void completer done: true
void completeError(Object error, [StackTrace? stackTrace])

Complete future with an error.

Calling complete or completeError must be done at most once.

Completing a future with an error indicates that an exception was thrown while trying to produce a value.

If error is a Future, the future itself is used as the error value. If you want to complete with the result of the future, you can use:

thisCompleter.complete(theFuture)

Or if you only want to handle an error from the future:

theFuture.catchError(thisCompleter.completeError);

The future must have an error handler installed before the call to completeError) or error will be considered an uncaught error.

void doStuff() {
  // Outputs a message like:
  // Uncaught Error: Assertion failed: "future not consumed"
  Completer().completeError(AssertionError('future not consumed'));
}

You can install an error handler through Future.catchError, Future.then or the await operation.

void doStuff() {
  final c = Completer();
  c.future.catchError((e) {
    // Handle the error.
  });
  c.completeError(AssertionError('future not consumed'));
}
Example
import 'raya:async';

Future<void> main() async {
  final c = Completer<String>();
  Timer.run(() => c.completeError(StateError('connection refused')));
  try {
    await c.future;
  } on StateError catch (e) {
    print('caught: ${e.message}');
  }
  print('isCompleted: ${c.isCompleted}');
}
Output
caught: connection refused
isCompleted: true
extension FutureIterable<T> on Iterable<Future<T>>
Example
import 'raya:async';

Future<int> square(int n) async => n * n;

Future<void> main() async {
  final results = await [for (var i = 1; i <= 4; i++) square(i)].wait;
  print('squares: $results');
  try {
    await [square(2), Future<int>.error('bad input'), square(3)].wait;
  } on ParallelWaitError<List<int?>, List<AsyncError?>> catch (e) {
    print('values: ${e.values}');
    print('errors: ${e.errors.map((x) => x?.error).toList()}');
  }
}
Output
squares: [1, 4, 9, 16]
values: [4, null, 9]
errors: [null, bad input, null]

Properties

waitgetter
Future<List<T>> get wait

Waits for futures in parallel.

Waits for all the futures in this iterable. Returns a list of the resulting values, in the same order as the futures which created them, if all futures are successful.

Similar to Future.wait, but reports errors using a ParallelWaitError, which allows the caller to handle errors and dispose successful results if necessary.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If any future completes with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a list of the values for successful futures and null for futures with errors. The ParallelWaitError.errors is a list of the same length, with null values for the successful futures and an AsyncError with the error for futures which completed with an error.

Example
import 'raya:async';

Future<void> main() async {
  final values = await [Future.value(1), Future.value(2), Future.value(3)].wait;
  print('wait on a list: $values');
  final (a, b) = await (Future.value('x'), Future.value(42)).wait;
  print('wait on a record: $a, $b');
}
Output
wait on a list: [1, 2, 3]
wait on a record: x, 42
extension

FutureRecord2

extension FutureRecord2<T1, T2> on (Future<T1>, Future<T2>)

Parallel operations on a record of futures.

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

Example
import 'raya:async';

Future<void> main() async {
  final (name, age) = await (Future.value('Ada'), Future.value(36)).wait;
  print('name: $name, age: $age');
  try {
    await (Future.value(1), Future<String>.error('lost')).wait;
  } on ParallelWaitError<(int?, String?), (AsyncError?, AsyncError?)> catch (e) {
    print('values: ${e.values}');
    print('second error: ${e.errors.$2?.error}');
  }
}
Output
name: Ada, age: 36
values: (1, null)
second error: lost

Properties

waitgetter
Future<(T1, T2)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord3

extension FutureRecord3<T1, T2, T3> on (Future<T1>, Future<T2>, Future<T3>)

Parallel operations on a record of futures.

Example
import 'raya:async';

Future<void> main() async {
  final (a, b, c) = await (Future.value(1), Future.value('two'), Future.value(3.0)).wait;
  print('a: $a, b: $b, c: $c');
  print('types: ${a.runtimeType}, ${b.runtimeType}, ${c.runtimeType}');
}
Output
a: 1, b: two, c: 3.0
types: int, String, double

Properties

waitgetter
Future<(T1, T2, T3)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord4

extension FutureRecord4<T1, T2, T3, T4> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord5

extension FutureRecord5<T1, T2, T3, T4, T5> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>, Future<T5>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4, T5)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord6

extension FutureRecord6<T1, T2, T3, T4, T5, T6> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>, Future<T5>, Future<T6>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4, T5, T6)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord7

extension FutureRecord7<T1, T2, T3, T4, T5, T6, T7> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>, Future<T5>, Future<T6>, Future<T7>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4, T5, T6, T7)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord8

extension FutureRecord8<T1, T2, T3, T4, T5, T6, T7, T8> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>, Future<T5>, Future<T6>, Future<T7>, Future<T8>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4, T5, T6, T7, T8)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

extension

FutureRecord9

extension FutureRecord9<T1, T2, T3, T4, T5, T6, T7, T8, T9> on (Future<T1>, Future<T2>, Future<T3>, Future<T4>, Future<T5>, Future<T6>, Future<T7>, Future<T8>, Future<T9>)

Parallel operations on a record of futures.

Properties

waitgetter
Future<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> get wait

Waits for futures in parallel.

Waits for all the futures in this record. Returns a record of the values, if all futures are successful.

The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.

If some futures complete with an error, the returned future completes with a ParallelWaitError. The ParallelWaitError.values is a record of the values of successful futures, and null for futures with errors. The ParallelWaitError.errors is a record of the same shape, with null values for the successful futures and an AsyncError with the error of futures which completed with an error.

class ParallelWaitError<V, E> extends Error

Error thrown when waiting for multiple futures, when some have errors.

The V and E types will have the same basic shape as the original collection of futures that was waited on.

For example, if the original awaited futures were a record (Future<T1>... Future<Tn>), the type V will be (T1?... Tn?) which allows keeping the values of futures that completed with a value, and E will be (AsyncError?... AsyncError?), also with n fields, which can contain the errors for the futures which completed with an error.

Waiting for a list or iterable of futures should provide a list of nullable values and errors of the same length.

Example
import 'raya:async';

Future<void> main() async {
  try {
    await [Future.value(1), Future<int>.error('e2'), Future<int>.error('e3')].wait;
  } on ParallelWaitError catch (e) {
    print('values: ${e.values}');
    print('error count in message: $e');
  }
  final manual = ParallelWaitError([1, null], [null, 'boom']);
  print('manual: ${manual.values} / ${manual.errors}');
}
Output
values: [1, null, null]
error count in message: ParallelWaitError(2 errors): e2
manual: [1, null] / [null, boom]

Constructors

ParallelWaitError(this.values, this.errors, {@Since("3.4") this._errorCount, @Since("3.4") this._defaultError})

Creates error with the provided values and errors.

If _defaultError is provided, its AsyncError.error is used in the toString of this parallel error, and its AsyncError.stackTrace is returned by stackTrace.

If _errorCount is provided, and it's greater than one, the number is reported in the toString.

Example
import 'raya:async';

Future<void> main() async {
  try {
    await [Future.value(1), Future<int>.error('e2'), Future<int>.error('e3')].wait;
  } on ParallelWaitError catch (e) {
    print('values: ${e.values}');
    print('error count in message: $e');
  }
  final manual = ParallelWaitError([1, null], [null, 'boom']);
  print('manual: ${manual.values} / ${manual.errors}');
}
Output
values: [1, null, null]
error count in message: ParallelWaitError(2 errors): e2
manual: [1, null] / [null, boom]

Properties

valuesfield
final V values

Values of successful futures.

Has the same shape as the original collection of futures, with values for each successful future and null values for each failing future.

errorsfield
final E errors

Errors of failing futures.

Has the same shape as the original collection of futures, with errors, typically AsyncError, for each failing future and null values for each successful future.

StackTrace? get stackTrace

Methods

toStringmethod
String toString()
Example
import 'raya:async';

Future<void> main() async {
  try {
    await [Future<int>.error('a'), Future<int>.error('b')].wait;
  } on ParallelWaitError catch (e) {
    print(e.toString());
  }
}
Output
ParallelWaitError(2 errors): a
class

Stream

abstract mixin class Stream<T>

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 an element 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 an async* function, which then returns a stream. Consuming that stream will lead the function to emit events until it ends, and the stream closes. You consume a stream either using an await for loop, which is available inside an async or async* function, or by forwarding its events directly using yield* inside an async* 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 a Stream<T> object. Then nothing further happens until someone tries to consume that stream. At that point, the body of the async* function starts running. If the convert function was omitted, the yield* will listen to the source stream and forward all events, date and errors, to the returned stream. When the source stream closes, the yield* is done, and the optionalMap function body ends too. This closes the returned stream. If a convert is supplied, the function instead listens on the source stream and enters an await for loop which repeatedly waits for the next data event. On a data event, it calls convert with the value and emits the result on the returned stream. If no error events are emitted by the source stream, the loop ends when the source stream does, then the optionalMap function body completes, which closes the returned stream. On an error event from the source stream, the await for re-throws that error, which breaks the loop. The error then reaches the end of the optionalMap function body, since it's not caught. That makes the error be emitted on the returned stream, which then closes.

The Stream class also provides functionality which allows you to manually listen for events from a stream, or to convert a stream into another stream or into a future.

The forEach function corresponds to the await for loop, just as Iterable.forEach corresponds to a normal for/in loop. Like the loop, it will call a function for each data event and break on an error.

The more low-level listen method is what every other method is based on. You call listen on a stream to tell it that you want to receive events, and to register the callbacks which will receive those events. When you call listen, you receive a StreamSubscription object which 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 whole lifetime 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 an async* 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 after the first subscription has been canceled.

Single-subscription streams are generally used for streaming chunks of larger 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.

If several listeners want to listen to a single-subscription stream, use asBroadcastStream to create a broadcast stream on top of the non-broadcast stream.

On either kind of stream, stream transformations, such as where and skip, 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 stream containing only the events that have not yet been emitted when the listen call occurs. For example the first getter listens to the stream, then returns the first event that listener receives. This is not necessarily the first even emitted by the stream, but the first of the remaining events of the broadcast stream.

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 to a broadcast stream after this point is allowed, but they will just receive a new "done" event as soon as possible.

Stream subscriptions 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.

The default implementation of isBroadcast returns false. A broadcast stream inheriting from Stream must override isBroadcast to return true if it wants to signal that it behaves like a broadcast stream.

Example
import 'raya:async';

// An async* generator produces a stream; yield* forwards another stream.
Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    yield i;
  }
}

Stream<String> launch() async* {
  yield* countdown(3).map((i) => '$i...');
  yield 'lift off';
}

Future<void> main() async {
  await for (final s in launch()) print(s);
}
Output
3...
2...
1...
lift off

Constructors

Streamconstructor
const Stream()
Example
import 'raya:async';

// Subclass Stream by implementing listen; here we delegate to a list.
class Countdown extends Stream<int> {
  final int from;
  Countdown(this.from);
  @override
  StreamSubscription<int> listen(void Function(int)? onData,
          {Function? onError, void Function()? onDone, bool? cancelOnError}) =>
      Stream.fromIterable([for (var i = from; i >= 0; i--) i])
          .listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}

Future<void> main() async {
  print('countdown: ${await Countdown(5).toList()}');
  print('sum: ${await Countdown(3).fold<int>(0, (a, b) => a + b)}');
}
Output
countdown: [5, 4, 3, 2, 1, 0]
sum: 6
const factory Stream.empty({@Since("3.2") bool broadcast}) = _EmptyStream<T>

Creates an empty broadcast stream.

This is a stream which does nothing except sending a done event when it's listened to.

Example:

const stream = Stream.empty();
stream.listen(
  (value) {
    throw "Unreachable";
  },
  onDone: () {
    print('Done');
  },
);

The stream defaults to being a broadcast stream, as reported by isBroadcast. This value can be changed by passing false as the broadcast parameter, which defaults to true.

The stream can be listened to more than once, whether it reports itself as broadcast or not.

Example
import 'raya:async';

Future<void> main() async {
  final s = Stream<int>.empty();
  print('toList: ${await s.toList()}');
  print('isEmpty: ${await Stream<int>.empty().isEmpty}');
  Stream<int>.empty().listen((_) => print('never'), onDone: () => print('done fires at once'));
  await Future.value();
  print('broadcast: ${Stream<int>.empty(broadcast: true).isBroadcast}');
}
Output
toList: []
isEmpty: true
done fires at once
broadcast: true
factory Stream.value(T value)

Creates a stream which emits a single data event before closing.

This stream emits a single data event of value and then closes with a done event.

Example:

Future<void> printThings(Stream<String> data) async {
  await for (var x in data) {
    print(x);
  }
}
printThings(Stream<String>.value('ok')); // prints "ok".

The returned stream is effectively equivalent to one created by ( async* { yield value; } ) or Future<T>.value(value).asStream.

Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.value('hello');
  print('events: ${await s.toList()}');
  print('single: ${await Stream.value(42).single}');
}
Output
events: [hello]
single: 42
factory Stream.error(Object error, [StackTrace? stackTrace])

Creates a stream which emits a single error event before completing.

This stream emits a single error event of error and stackTrace and then completes with a done event.

Example:

Future<void> tryThings(Stream<int> data) async {
  try {
    await for (var x in data) {
      print('Data: $x');
    }
  } catch (e) {
    print(e);
  }
}
tryThings(Stream<int>.error('Error')); // prints "Error".

The returned stream is effectively equivalent to one created by Future<T>.error(error, stackTrace).asStream, by or ( async* { throw error; } ), except that you can control the stack trace as well.

Example
import 'raya:async';

Future<void> main() async {
  Stream<int>.error(StateError('no data')).listen(
    (v) => print('data $v'),
    onError: (Object e) => print('error event: $e'),
    onDone: () => print('done'),
  );
  await Future.delayed(Duration.zero);
  final r = await Stream<int>.error('x').toList().catchError((Object e) => <int>[-1]);
  print('toList recovered: $r');
}
Output
error event: Bad state: no data
done
toList recovered: [-1]
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.

Example:

Future<String> futureTask() async {
  await Future.delayed(const Duration(seconds: 5));
  return 'Future complete';
}

final stream = Stream<String>.fromFuture(futureTask());
stream.listen(print,
    onDone: () => print('Done'), onError: print);

// Outputs:
// "Future complete" after 'futureTask' finished.
// "Done" when stream completed.
Example
import 'raya:async';

Future<String> fetchTitle() async => 'Raya docs';

Future<void> main() async {
  final s = Stream.fromFuture(fetchTitle());
  await for (final t in s) {
    print('event: $t');
  }
  final upper = await Stream.fromFuture(fetchTitle()).map((t) => t.toUpperCase()).first;
  print('mapped: $upper');
}
Output
event: Raya docs
mapped: RAYA DOCS
factory Stream.fromFutures(Iterable<Future<T>> futures)

Create a single-subscription stream from a group of futures.

The stream reports the results of the futures on the stream in the order in which the futures complete. Each future provides either a data event or an error event, depending on how the future completes.

If some futures have already completed when Stream.fromFutures is called, their results will be emitted in some unspecified order.

When all futures have completed, the stream is closed.

If futures is empty, the stream closes as soon as possible.

Example:

Future<int> waitTask() async {
  await Future.delayed(const Duration(seconds: 2));
  return 10;
}

Future<String> doneTask() async {
  await Future.delayed(const Duration(seconds: 5));
  return 'Future complete';
}

final stream = Stream<Object>.fromFutures([doneTask(), waitTask()]);
stream.listen(print, onDone: () => print('Done'), onError: print);

// Outputs:
// 10 after 'waitTask' finished.
// "Future complete" after 'doneTask' finished.
// "Done" when stream completed.
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromFutures([
    Future.delayed(const Duration(milliseconds: 30), () => 'third'),
    Future.delayed(const Duration(milliseconds: 1), () => 'first'),
    Future.delayed(const Duration(milliseconds: 15), () => 'second'),
  ]);
  // Events arrive in completion order, not list order.
  print('events: ${await s.toList()}');
}
Output
events: [first, second, third]
factory Stream.fromIterable(Iterable<T> elements)

Creates a stream that gets its data from elements.

The iterable is iterated when the stream receives a listener, and stops iterating if the listener cancels the subscription, or if the Iterator.moveNext method returns false or throws. Iteration is suspended while the stream subscription is paused.

If calling Iterator.moveNext on elements.iterator throws, the stream emits that error and then it closes. If reading Iterator.current on elements.iterator throws, the stream emits that error, but keeps iterating.

Can be listened to more than once. Each listener iterates elements independently.

Example:

final numbers = [1, 2, 3, 5, 6, 7];
final stream = Stream.fromIterable(numbers);
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([1, 2, 3, 4, 5]);
  await for (final x in s) {
    print('got $x');
  }
  print('sum: ${await Stream.fromIterable([1, 2, 3]).reduce((a, b) => a + b)}');
}
Output
got 1
got 2
got 3
got 4
got 5
sum: 6
factory Stream.multi(void Function(MultiStreamController<T>) onListen, {bool isBroadcast = false})

Creates a multi-subscription stream.

Each time the created stream is listened to, the onListen callback is invoked with a new MultiStreamController, which forwards events to the StreamSubscription returned by that listen call.

This allows each listener to be treated as an individual stream.

The MultiStreamController does not support reading its StreamController.stream. Setting its StreamController.onListen has no effect since the onListen callback is called instead, and the StreamController.onListen won't be called later. The controller acts like an asynchronous controller, but provides extra methods for delivering events synchronously.

If isBroadcast is set to true, the returned stream's Stream.isBroadcast will be true. This has no effect on the stream behavior, it is up to the onListen function to act like a broadcast stream if it claims to be one.

A multi-subscription stream can behave like any other stream. If the onListen callback throws on every call after the first, the stream behaves like a single-subscription stream. If the stream emits the same events to all current listeners, it behaves like a broadcast stream.

It can also choose to emit different events to different listeners. For example, a stream which repeats the most recent non-null event to new listeners, could be implemented as this example:

extension StreamRepeatLatestExtension<T extends Object> on Stream<T> {
  Stream<T> repeatLatest() {
    var done = false;
    T? latest = null;
    var currentListeners = <MultiStreamController<T>>{};
    this.listen((event) {
      latest = event;
      for (var listener in [...currentListeners]) listener.addSync(event);
    }, onError: (Object error, StackTrace stack) {
      for (var listener in [...currentListeners]) listener.addErrorSync(error, stack);
    }, onDone: () {
      done = true;
      latest = null;
      for (var listener in currentListeners) listener.closeSync();
      currentListeners.clear();
    });
    return Stream.multi((controller) {
      if (done) {
        controller.close();
        return;
      }
      currentListeners.add(controller);
      var latestValue = latest;
      if (latestValue != null) controller.add(latestValue);
      controller.onCancel = () {
        currentListeners.remove(controller);
      };
    });
  }
}
Example
import 'raya:async';

Future<void> main() async {
  var listeners = 0;
  final s = Stream<String>.multi((c) {
    final id = ++listeners;
    c.add('hello listener $id');
    c.close();
  });
  print(await s.toList());
  print(await s.toList()); // each listener gets its own controller
}
Output
[hello listener 1]
[hello listener 2]
factory Stream.periodic(Duration period, [T computation(int computationCount)?])

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.

The period must be a non-negative Duration.

If computation is omitted, the event values will all be null.

The computation must not be omitted if the event type T does not allow null as a value.

Example:

final stream =
    Stream<int>.periodic(const Duration(
        seconds: 1), (count) => count * count).take(5);

stream.forEach(print); // Outputs event values 0,1,4,9,16.
Example
import 'raya:async';

Future<void> main() async {
  final ticks = Stream.periodic(const Duration(milliseconds: 10), (i) => 'tick $i').take(3);
  await for (final t in ticks) print(t);
}
Output
tick 0
tick 1
tick 2
factory Stream.eventTransformed(Stream<dynamic> source, EventSink<dynamic> mapSink(EventSink<T> sink))

Creates a stream where all events of an existing stream are piped through a sink-transformation.

The given mapSink closure is invoked when the returned stream is listened to. All events from the source are added into the event sink that is returned from the invocation. The transformation puts all transformed events into the sink the mapSink closure received during its invocation. Conceptually the mapSink creates a transformation pipe with the input sink being the returned EventSink and the output sink being the sink it received.

This constructor is frequently used to build transformers.

Example use for a duplicating transformer:

class DuplicationSink implements EventSink<String> {
  final EventSink<String> _outputSink;
  DuplicationSink(this._outputSink);

  void add(String data) {
    _outputSink.add(data);
    _outputSink.add(data);
  }

  void addError(e, [st]) { _outputSink.addError(e, st); }
  void close() { _outputSink.close(); }
}

class DuplicationTransformer extends StreamTransformerBase<String, String> {
  // Some generic types omitted for brevity.
  Stream bind(Stream stream) => Stream<String>.eventTransformed(
      stream,
      (EventSink sink) => DuplicationSink(sink));
}

stringStream.transform(DuplicationTransformer());

The resulting stream is a broadcast stream if source is.

Example
import 'raya:async';

class DoublingSink implements EventSink<int> {
  final EventSink<int> out;
  DoublingSink(this.out);
  void add(int e) => out.add(e * 2);
  void addError(Object e, [StackTrace? st]) => out.addError(e, st);
  void close() => out.close();
}

Future<void> main() async {
  final source = Stream.fromIterable([1, 2, 3]);
  final doubled = Stream<int>.eventTransformed(source, (sink) => DoublingSink(sink));
  print('doubled: ${await doubled.toList()}');
}
Output
doubled: [2, 4, 6]

Static

castFromstaticmethod
static Stream<T> castFrom<S, T>(Stream<S> source)

Adapts source to be a Stream<T>.

This allows source to be used at the new type, but at run-time it must satisfy the requirements of both the new type and its original type.

Data events created by the source stream must also be instances of T.

Example
import 'raya:async';

Future<void> main() async {
  final Stream<Object> objs = Stream.fromIterable(<Object>[1, 2, 3]);
  final ints = Stream.castFrom<Object, int>(objs);
  print('is Stream<int>: ${ints is Stream<int>}');
  print('sum: ${await ints.fold<int>(0, (a, b) => a + b)}');
  final words = Stream.castFrom<Object, String>(Stream.fromIterable(<Object>['a', 'b']));
  print('joined: ${await words.join('+')}');
}
Output
is Stream<int>: true
sum: 6
joined: a+b

Properties

bool get isBroadcast

Whether this stream is a broadcast stream.

lengthgetter
Future<int> get length

The number of elements in this stream.

Waits for all elements of this stream. When this stream ends, the returned future is completed with the number of elements.

If this stream emits an error, the returned future is completed with that error, and processing stops.

This operation listens to this stream, and a non-broadcast stream cannot be reused after finding its length.

isEmptygetter
Future<bool> get isEmpty

Whether this stream contains any elements.

Waits for the first element of this stream, then completes the returned future with false. If this stream ends without emitting any elements, the returned future is completed with true.

If the first event is an error, the returned future is completed with that error.

This operation listens to this stream, and a non-broadcast stream cannot be reused after checking whether it is empty.

firstgetter
Future<T> get first

The first element of this stream.

Stops listening to this stream after the first element has been received.

Internally the method cancels its subscription after the first element. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this getter.

If an error event occurs before the first data event, the returned future is completed with that error.

If this stream is empty (a done event occurs before the first data event), the returned future completes with an error.

Except for the type of the error, this method is equivalent to this.elementAt(0).

lastgetter
Future<T> get last

The last element of this stream.

If this stream emits an error event, the returned future is completed with that error and processing stops.

If this stream is empty (the done event is the first event), the returned future completes with an error.

singlegetter
Future<T> get single

The single element of this stream.

If this stream emits an error event, the returned future is completed with that error and processing stops.

If this Stream is empty or has more than one element, the returned future completes with an error.

Methods

Stream<T> asBroadcastStream({void onListen(StreamSubscription<T> subscription)?, void onCancel(StreamSubscription<T> subscription)?})

Returns a multi-subscription stream that produces the same events as this.

The returned stream 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 listeners. 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.

Cancelling is intended to be used when there are no current subscribers. If the subscription passed to onListen or onCancel is cancelled, then no further events are ever emitted by current subscriptions on the returned broadcast stream, not even a done event.

Example:

final stream =
    Stream<int>.periodic(const Duration(seconds: 1), (count) => count)
        .take(10);

final broadcastStream = stream.asBroadcastStream(
  onCancel: (controller) {
    print('Stream paused');
    controller.pause();
  },
  onListen: (controller) async {
    if (controller.isPaused) {
      print('Stream resumed');
      controller.resume();
    }
  },
);

final oddNumberStream = broadcastStream.where((event) => event.isOdd);
final oddNumberListener = oddNumberStream.listen(
      (event) {
    print('Odd: $event');
  },
  onDone: () => print('Done'),
);

final evenNumberStream = broadcastStream.where((event) => event.isEven);
final evenNumberListener = evenNumberStream.listen((event) {
  print('Even: $event');
}, onDone: () => print('Done'));

await Future.delayed(const Duration(milliseconds: 3500)); // 3.5 second
// Outputs:
// Even: 0
// Odd: 1
// Even: 2
oddNumberListener.cancel(); // Nothing printed.
evenNumberListener.cancel(); // "Stream paused"
await Future.delayed(const Duration(seconds: 2));
print(await broadcastStream.first); // "Stream resumed"
// Outputs:
// 3
Example
import 'raya:async';

Future<void> main() async {
  final single = Stream.fromIterable([1, 2, 3]);
  final b = single.asBroadcastStream();
  print('isBroadcast: ${single.isBroadcast} -> ${b.isBroadcast}');
  final a = <int>[], c = <int>[];
  b.listen(a.add);
  b.listen(c.add); // a second listener is allowed now
  await Future.delayed(Duration.zero);
  print('listener A: $a, listener B: $c');
}
Output
isBroadcast: false -> true
listener A: [1, 2, 3], listener B: [1, 2, 3]
listenmethod
StreamSubscription<T> listen(void onData(T event)?, {Function? onError, void onDone()?, bool? cancelOnError})

Adds a subscription to this stream.

Returns a StreamSubscription which handles events from this stream using the provided onData, onError and onDone handlers. The handlers can be changed on the subscription, but they start out as the provided functions.

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 called with the error object and possibly a stack trace.

The onError callback must be of type void Function(Object error) or void Function(Object error, StackTrace). The function type determines whether onError is invoked with a stack trace argument. The stack trace argument may be StackTrace.empty if this stream received an error without a stack trace.

Otherwise it is called with just the error object. If onError is omitted, any errors on this stream are considered unhandled, and will be passed to the current Zone's error handler. By default unhandled async errors are treated as if they were uncaught top-level errors.

If this stream closes and sends a done event, the onDone handler is called. If onDone is null, nothing happens.

If cancelOnError is true, the subscription is automatically canceled when the first error event is delivered. The default is false.

While a subscription is paused, or when it has been canceled, the subscription doesn't receive events and none of the event handler functions are called.

Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<void>();
  Stream.fromIterable(['a', 'b', 'c']).listen(
    (x) => print('data: $x'),
    onDone: () {
      print('done');
      done.complete();
    },
  );
  await done.future;
}
Output
data: a
data: b
data: c
done
wheremethod
Stream<T> where(bool test(T event))

Creates a new stream from this stream that discards some elements.

The new stream sends the same error and done events as this stream, but it only sends the data events that satisfy the test.

If the test function throws, the data event is dropped and the error is emitted on the returned stream instead.

The returned stream is a broadcast stream if this stream is. If a broadcast stream is listened to more than once, each subscription will individually perform the test.

Example:

final stream =
    Stream<int>.periodic(const Duration(seconds: 1), (count) => count)
        .take(10);

final customStream = stream.where((event) => event > 3 && event <= 6);
customStream.listen(print); // Outputs event values: 4,5,6.
Example
import 'raya:async';

Future<void> main() async {
  final words = Stream.fromIterable(['apple', 'bob', 'civic', 'raya', 'level']);
  final palindromes = words.where((w) => w == w.split('').reversed.join());
  print(await palindromes.toList());
}
Output
[bob, civic, level]
mapmethod
Stream<S> map<S>(S convert(T event))

Transforms each element of this stream into a new stream event.

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

For each data event, o, in this stream, the returned stream provides a data event with the value convert(o). If convert throws, the returned stream reports it as an error event instead.

Error and done events are passed through unchanged to the returned stream.

The returned stream is a broadcast stream if this stream is. The convert function is called once per data event per listener. If a broadcast stream is listened to more than once, each subscription will individually call convert on each data event.

Unlike transform, this method does not treat the stream as chunks of a single value. Instead each event is converted independently of the previous and following events, which may not always be correct. For example, UTF-8 encoding, or decoding, will give wrong results if a surrogate pair, or a multibyte UTF-8 encoding, is split into separate events, and those events are attempted encoded or decoded independently.

Example:

final stream =
    Stream<int>.periodic(const Duration(seconds: 1), (count) => count)
        .take(5);

final calculationStream =
    stream.map<String>((event) => 'Square: ${event * event}');
calculationStream.forEach(print);
// Square: 0
// Square: 1
// Square: 4
// Square: 9
// Square: 16
Example
import 'raya:async';

Future<void> main() async {
  final out = await Stream.fromIterable([1, 2, 3, 4, 5, 6])
      .where((x) => x.isEven)
      .map((x) => x * x)
      .toList();
  print('even squares: $out');
}
Output
even squares: [4, 16, 36]
asyncMapmethod
Stream<E> asyncMap<E>(FutureOr<E> convert(T event))

Creates a new stream with each data event of this stream asynchronously mapped to a new event.

This acts like map, in that convert function is called once per data event, but here convert may be asynchronous and return a Future. If that happens, this stream waits for that future to complete before continuing with further events.

The returned stream is a broadcast stream if this stream is.

Example
import 'raya:async';

Future<int> lookup(int id) async => id * 100;

Future<void> main() async {
  final out = await Stream.fromIterable([1, 2, 3]).asyncMap(lookup).toList();
  print('asyncMap: $out');
}
Output
asyncMap: [100, 200, 300]
Stream<E> asyncExpand<E>(Stream<E>? convert(T event))

Transforms each element into a sequence of asynchronous events.

Returns a new stream and for each event of this stream, do the following:

  • If the event is an error event or a done event, it is emitted directly by the returned stream.
  • Otherwise it is an element. Then the convert function is called with the element as argument to produce a convert-stream for the element.
  • If that call throws, the error is emitted on the returned stream.
  • If the call returns null, no further action is taken for the elements.
  • Otherwise, this stream is paused and convert-stream is listened to. Every data and error event of the convert-stream is emitted on the returned stream in the order it is produced. When the convert-stream ends, this stream is resumed.

The returned stream is a broadcast stream if this stream is.

Example
import 'raya:async';

Stream<String> pages(String book) => Stream.fromIterable(['$book p1', '$book p2']);

Future<void> main() async {
  final all = Stream.fromIterable(['A', 'B']).asyncExpand(pages);
  print('pages: ${await all.toList()}');
}
Output
pages: [A p1, A p2, B p1, B p2]
Stream<T> handleError(Function onError, {bool test(error)?})

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 onError function.

The onError callback must be of type void Function(Object error) or void Function(Object error, StackTrace). The function type determines whether onError is invoked with a stack trace argument. The stack trace argument may be StackTrace.empty if this stream received an error without a stack trace.

An asynchronous error error is matched by a test function if test(error) returns true. If test is omitted, every error is considered matching.

If the error is intercepted, the onError 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 this stream forget the error. If the received error value is thrown again by the onError function, it acts like a rethrow and it is emitted along with its original stack trace, not the stack trace of the throw inside onError.

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.

The returned stream is a broadcast stream if this stream is. If a broadcast stream is listened to more than once, each subscription will individually perform the test and handle the error.

Example:

Stream.periodic(const Duration(seconds: 1), (count) {
  if (count == 2) {
    throw Exception('Exceptional event');
  }
  return count;
}).take(4).handleError(print).forEach(print);

// Outputs:
// 0
// 1
// Exception: Exceptional event
// 3
// 4
Example
import 'raya:async';

Stream<int> readings() async* {
  yield 1;
  yield* Stream.error(FormatException('garbled'));
  yield 3;
}

Future<void> main() async {
  final clean = readings().handleError((Object e) => print('skipped: $e'));
  print('values: ${await clean.toList()}');
  // test: only handle some errors; others still propagate.
  final r = await readings()
      .handleError((e) {}, test: (e) => e is StateError)
      .toList()
      .catchError((Object e) => <int>[-1]);
  print('unhandled type propagates: $r');
}
Output
skipped: FormatException: garbled
values: [1, 3]
unhandled type propagates: [-1]
expandmethod
Stream<S> expand<S>(Iterable<S> convert(T element))

Transforms each element of this stream into a sequence of elements.

Returns a new stream where each element of this stream is replaced by zero or more data events. The event values are provided as an Iterable by a call to convert with the element as argument, and the elements of that iterable is emitted in iteration order. If calling convert throws, or if the iteration of the returned values throws, the error is emitted on the returned stream and iteration ends for that element of this stream.

Error events and the done event of this stream are forwarded directly to the returned stream.

The returned stream is a broadcast stream if this stream is. If a broadcast stream is listened to more than once, each subscription will individually call convert and expand the events.

Example
import 'raya:async';

Future<void> main() async {
  final words = Stream.fromIterable(['hi there', 'raya']).expand((line) => line.split(' '));
  print('words: ${await words.toList()}');
  final dup = Stream.fromIterable([1, 2]).expand((n) => [n, n]);
  print('duplicated: ${await dup.toList()}');
  final none = Stream.fromIterable([1, 2]).expand((n) => <int>[]);
  print('empty expansion: ${await none.toList()}');
}
Output
words: [hi, there, raya]
duplicated: [1, 1, 2, 2]
empty expansion: []
pipemethod
Future pipe(StreamConsumer<T> streamConsumer)

Pipes the events of this stream into streamConsumer.

All events of this stream are added to streamConsumer using StreamConsumer.addStream. The streamConsumer is closed when this stream has been successfully added to it - when the future returned by addStream completes without an error.

Returns a future which completes when this stream has been consumed and the consumer has been closed.

The returned future completes with the same result as the future returned by StreamConsumer.close. If the call to StreamConsumer.addStream fails in some way, this method fails in the same way.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final collected = c.stream.toList();
  // pipe sends every event into the consumer, then closes it.
  await Stream.fromIterable([1, 2, 3]).pipe(c);
  print('piped: ${await collected}');
}
Output
piped: [1, 2, 3]
transformmethod
Stream<S> transform<S>(StreamTransformer<T, S> streamTransformer)

Applies streamTransformer to this stream.

Returns the transformed stream, that is, the result of streamTransformer.bind(this). This method simply allows writing the call to streamTransformer.bind in a chained fashion, like

stream.map(mapping).transform(transformation).toList()

Which can be more convenient than calling bind directly.

The streamTransformer can return any stream. Whether the returned stream is a broadcast stream or not, and which elements it will contain, is entirely up to the transformation.

This method should always be used for transformations which treat the entire stream as representing a single value which has perhaps been split into several parts for transport, like a file being read from disk or being fetched over a network. The transformation will then produce a new stream which transforms the stream's value incrementally (perhaps using Converter.startChunkedConversion). The resulting stream may again be chunks of the result, but does not have to correspond to specific events from the source string.

Example
import 'raya:async';

Future<void> main() async {
  final evens = StreamTransformer<int, int>.fromHandlers(handleData: (n, sink) {
    if (n.isEven) sink.add(n);
  });
  final out = Stream.fromIterable([1, 2, 3, 4, 5, 6]).transform(evens);
  print('evens: ${await out.toList()}');
}
Output
evens: [2, 4, 6]
reducemethod
Future<T> reduce(T combine(T previous, T element))

Combines a sequence of values by repeatedly applying combine.

Similar to Iterable.reduce, this function maintains a value, starting with the first element of this stream and updated for each further element of this stream. For each element after the first, the value is updated to the result of calling combine with the previous value and the element.

When this stream is done, the returned future is completed with the value at that time.

If this stream is empty, the returned future is completed with an error. If this stream emits an error, or the call to combine throws, the returned future is completed with that error, and processing is stopped.

Example:

final result = await Stream.fromIterable([2, 6, 10, 8, 2])
    .reduce((previous, element) => previous + element);
print(result); // 28
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([3, 9, 4, 7]);
  print('max: ${await s.reduce((a, b) => a > b ? a : b)}');
  print('product: ${await Stream.fromIterable([1, 2, 3, 4]).reduce((a, b) => a * b)}');
  final r = await Stream<int>.empty().reduce((a, b) => a + b).catchError((Object e) => -1);
  print('empty stream -> error, recovered as $r');
}
Output
max: 9
product: 24
empty stream -> error, recovered as -1
foldmethod
Future<S> fold<S>(S initialValue, S combine(S previous, T element))

Combines a sequence of values by repeatedly applying combine.

Similar to Iterable.fold, this function maintains a value, starting with initialValue and updated for each element of this stream. For each element, the value is updated to the result of calling combine with the previous value and the element.

When this stream is done, the returned future is completed with the value at that time. For an empty stream, the future is completed with initialValue.

If this stream emits an error, or the call to combine throws, the returned future is completed with that error, and processing is stopped.

Example:

final result = await Stream.fromIterable([2, 6, 10, 8, 2])
    .fold<int>(10, (previous, element) => previous + element);
print(result); // 38
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([3, 1, 4, 1, 5]);
  final total = await s.fold<int>(0, (a, b) => a + b);
  print('fold: $total');
  print('join: ${await Stream.fromIterable(['a', 'b']).join('+')}');
  print('length: ${await Stream.fromIterable([1, 2, 3]).length}');
}
Output
fold: 14
join: a+b
length: 3
joinmethod
Future<String> join([String separator = ""])

Combines the string representation of elements into a single string.

Each element is converted to a string using its Object.toString method. If separator is provided, it is inserted between element string representations.

The returned future is completed with the combined string when this stream is done.

If this stream emits an error, or the call to Object.toString throws, the returned future is completed with that error, and processing stops.

Example:

final result = await Stream.fromIterable(['Mars', 'Venus', 'Earth'])
    .join('--');
print(result); // 'Mars--Venus--Earth'
Example
import 'raya:async';

Future<void> main() async {
  print(await Stream.fromIterable(['a', 'b', 'c']).join());
  print(await Stream.fromIterable([1, 2, 3]).join(', '));
  print('[${await Stream<String>.empty().join('-')}]');
}
Output
abc
1, 2, 3
[]
containsmethod
Future<bool> contains(Object? needle)

Returns whether needle occurs in the elements provided by this stream.

Compares each element of this stream to needle using [Object.==]. If an equal element is found, the returned future is completed with true. If this stream ends without finding a match, the future is completed with false.

If this stream emits an error, or the call to [Object.==] throws, the returned future is completed with that error, and processing stops.

Example:

final result = await Stream.fromIterable(['Year', 2021, 12, 24, 'Raya'])
    .contains('Raya');
print(result); // true
Example
import 'raya:async';

Future<void> main() async {
  print('has 3: ${await Stream.fromIterable([1, 2, 3]).contains(3)}');
  print('has 9: ${await Stream.fromIterable([1, 2, 3]).contains(9)}');
  print('has "b": ${await Stream.fromIterable(['a', 'b']).contains('b')}');
}
Output
has 3: true
has 9: false
has "b": true
forEachmethod
Future<void> forEach(void action(T element))

Executes action on each element of this stream.

Completes the returned Future when all elements of this stream have been processed.

If this stream emits an error, or if the call to action throws, the returned future completes with that error, and processing stops.

Example
import 'raya:async';

Future<void> main() async {
  var total = 0;
  await Stream.fromIterable([5, 10, 15]).forEach((n) {
    total += n;
    print('saw $n');
  });
  print('total: $total');
}
Output
saw 5
saw 10
saw 15
total: 30
everymethod
Future<bool> every(bool test(T element))

Checks whether test accepts all elements provided by this stream.

Calls test on each element of this stream. If the call returns false, the returned future is completed with false and processing stops.

If this stream ends without finding an element that test rejects, the returned future is completed with true.

If this stream emits an error, or if the call to test throws, the returned future is completed with that error, and processing stops.

Example:

final result =
    await Stream.periodic(const Duration(seconds: 1), (count) => count)
        .take(15)
        .every((x) => x <= 5);
print(result); // false
Example
import 'raya:async';

Future<void> main() async {
  print('all positive: ${await Stream.fromIterable([1, 2, 3]).every((n) => n > 0)}');
  print('all even:     ${await Stream.fromIterable([2, 3, 4]).every((n) => n.isEven)}');
  print('empty stream: ${await Stream<int>.empty().every((n) => false)}');
}
Output
all positive: true
all even:     false
empty stream: true
anymethod
Future<bool> any(bool test(T element))

Checks whether test accepts any element provided by this stream.

Calls test on each element of this stream. If the call returns true, the returned future is completed with true and processing stops.

If this stream ends without finding an element that test accepts, the returned future is completed with false.

If this stream emits an error, or if the call to test throws, the returned future is completed with that error, and processing stops.

Example:

final result =
    await Stream.periodic(const Duration(seconds: 1), (count) => count)
        .take(15)
        .any((element) => element >= 5);

print(result); // true
Example
import 'raya:async';

Future<void> main() async {
  print('any > 2: ${await Stream.fromIterable([1, 2, 3]).any((n) => n > 2)}');
  print('any < 0: ${await Stream.fromIterable([1, 2, 3]).any((n) => n < 0)}');
  print('empty:   ${await Stream<int>.empty().any((n) => true)}');
}
Output
any > 2: true
any < 0: false
empty:   false
castmethod
Stream<R> cast<R>()

Adapt this stream to be a Stream<R>.

This stream is wrapped as a Stream<R> which checks at run-time that each data event emitted by this stream is also an instance of R.

Example
import 'raya:async';

Future<void> main() async {
  // A Stream<num> that only ever carries ints, viewed as a Stream<int>.
  final Stream<num> nums = Stream.fromIterable(<num>[1, 2, 3]);
  final Stream<int> ints = nums.cast<int>();
  print('ints: ${await ints.toList()}');
  print('type: ${ints is Stream<int>}');
  // Elements are checked one by one as they pass through.
  final doubled = nums.cast<int>().map((i) => i * 2);
  print('doubled: ${await doubled.toList()}');
}
Output
ints: [1, 2, 3]
type: true
doubled: [2, 4, 6]
toListmethod
Future<List<T>> toList()

Collects all elements of this stream in a List.

Creates a List<T> and adds all elements of this stream to the list in the order they arrive. When this stream ends, the returned future is completed with that list.

If this stream emits an error, the returned future is completed with that error, and processing stops.

Example
import 'raya:async';

Stream<int> squares(int n) async* {
  for (var i = 1; i <= n; i++) yield i * i;
}

Future<void> main() async {
  print('squares: ${await squares(5).toList()}');
  print('empty: ${await Stream<int>.empty().toList()}');
}
Output
squares: [1, 4, 9, 16, 25]
empty: []
toSetmethod
Future<Set<T>> toSet()

Collects the data of this stream in a Set.

Creates a Set<T> and adds all elements of this stream to the set. In the order they arrive. When this stream ends, the returned future is completed with that set.

The returned set is the same type as created by <T>{}. If another type of set is needed, either use forEach to add each element to the set, or use toList.then((list) => new SomeOtherSet.from(list)) to create the set.

If this stream emits an error, the returned future is completed with that error, and processing stops.

Example
import 'raya:async';

Future<void> main() async {
  final tags = Stream.fromIterable(['raya', 'docs', 'raya', 'async', 'docs']);
  print('unique: ${await tags.toSet()}');
}
Output
unique: {raya, docs, async}
drainmethod
Future<E> drain<E>([E? futureValue])

Discards all data on this stream, but signals when it is done or an error occurred.

When subscribing using drain, cancelOnError will be true. This means that the future will complete with the first error on this stream and then cancel the subscription.

If this stream emits an error, the returned future is completed with that error, and processing is stopped.

In case of a done event the future completes with the given futureValue.

The futureValue must not be omitted if null is not assignable to E.

Example:

final result = await Stream.fromIterable([1, 2, 3]).drain(100);
print(result); // Outputs: 100.
Example
import 'raya:async';

Future<void> main() async {
  var seen = 0;
  final s = Stream.fromIterable([1, 2, 3]).map((n) => seen += n);
  final r = await s.drain('finished'); // discard events, complete with a value
  print('drain result: $r, side effects ran: $seen');
}
Output
drain result: finished, side effects ran: 6
takemethod
Stream<T> take(int count)

Provides at most the first count data events of this stream.

Returns a stream that emits the same events that this stream would if listened to at the same time, until either this stream ends or it has emitted count data events, at which point the returned stream is done.

If this stream produces fewer than count data events before it's done, so will the returned stream.

Starts listening to this stream when the returned stream is listened to and stops listening when the first count data events have been received.

This means that if this is a single-subscription (non-broadcast) streams it cannot be reused after the returned stream has been listened to.

If this is a broadcast stream, the returned stream is a broadcast stream. In that case, the events are only counted from the time the returned stream is listened to.

Example:

final stream =
    Stream<int>.periodic(const Duration(seconds: 1), (i) => i)
        .take(60);
stream.forEach(print); // Outputs events: 0, ... 59.
Example
import 'raya:async';

Stream<int> naturals() async* {
  var n = 0;
  while (true) yield n++;
}

Future<void> main() async {
  print('take(5): ${await naturals().take(5).toList()}');
  print('skip(3).take(3): ${await naturals().skip(3).take(3).toList()}');
  print('first > 10: ${await naturals().firstWhere((n) => n > 10)}');
}
Output
take(5): [0, 1, 2, 3, 4]
skip(3).take(3): [3, 4, 5]
first > 10: 11
takeWhilemethod
Stream<T> takeWhile(bool test(T element))

Forwards data events while test is successful.

Returns a stream that provides the same events as this stream until test fails for a data event. The returned stream is done when either this stream is done, or when this stream first emits a data event that fails test.

The test call is considered failing if it returns a non-true value or if it throws. If the test call throws, the error is emitted as the last event on the returned streams.

Stops listening to this stream after the accepted elements.

Internally the method cancels its subscription after these elements. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this method.

The returned stream is a broadcast stream if this stream is. For a broadcast stream, the events are only tested from the time the returned stream is listened to.

Example:

final stream = Stream<int>.periodic(const Duration(seconds: 1), (i) => i)
    .takeWhile((event) => event < 6);
stream.forEach(print); // Outputs events: 0, ..., 5.
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([2, 4, 6, 7, 8]);
  print('leading evens: ${await s.takeWhile((n) => n.isEven).toList()}');
}
Output
leading evens: [2, 4, 6]
skipmethod
Stream<T> skip(int count)

Skips the first count data events from this stream.

Returns a stream that emits the same events as this stream would if listened to at the same time, except that the first count data events are not emitted. The returned stream is done when this stream is.

If this stream emits fewer than count data events before being done, the returned stream emits no data events.

The returned stream is a broadcast stream if this stream is. For a broadcast stream, the events are only counted from the time the returned stream is listened to.

Example:

final stream =
    Stream<int>.periodic(const Duration(seconds: 1), (i) => i).skip(7);
stream.forEach(print); // Skips events 0, ..., 6. Outputs events: 7, ...
Example
import 'raya:async';

Future<void> main() async {
  final lines = Stream.fromIterable(['header', 'row 1', 'row 2']);
  print('rows: ${await lines.skip(1).toList()}');
  print('skip more than length: ${await Stream.fromIterable([1, 2]).skip(5).toList()}');
}
Output
rows: [row 1, row 2]
skip more than length: []
skipWhilemethod
Stream<T> skipWhile(bool test(T element))

Skip data events from this stream while they are matched by test.

Returns a stream that emits the same events as this stream, except that data events are not emitted until a data event fails test. The test fails when called with a data event if it returns a non-true value or if the call to test throws. If the call throws, the error is emitted as an error event on the returned stream instead of the data event, otherwise the event that made test return non-true is emitted as the first data event.

Error and done events are provided by the returned stream unmodified.

The returned stream is a broadcast stream if this stream is. For a broadcast stream, the events are only tested from the time the returned stream is listened to.

Example:

final stream = Stream<int>.periodic(const Duration(seconds: 1), (i) => i)
    .take(10)
    .skipWhile((x) => x < 5);
stream.forEach(print); // Outputs events: 5, ..., 9.
Example
import 'raya:async';

Future<void> main() async {
  final log = Stream.fromIterable(['# a', '# b', 'start', '# c', 'end']);
  print('after comments: ${await log.skipWhile((l) => l.startsWith('#')).toList()}');
}
Output
after comments: [start, # c, end]
distinctmethod
Stream<T> distinct([bool equals(T previous, T next)?])

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 consecutive data events that are equal. That is, errors are passed through to the returned stream, and data events are passed through if they are distinct from the most recently emitted data event.

Equality is determined by the provided equals method. If that is omitted, the '==' operator on the last provided data element is used.

If equals throws, the data event is replaced by an error event containing the thrown error. The behavior is equivalent to the original stream emitting the error event, and it doesn't change what the most recently emitted data event is.

The returned stream is a broadcast stream if this stream is. If a broadcast stream is listened to more than once, each subscription will individually perform the equals test.

Example:

final stream = Stream.fromIterable([2, 6, 6, 8, 12, 8, 8, 2]).distinct();
stream.forEach(print); // Outputs events: 2,6,8,12,8,2.
Example
import 'raya:async';

Future<void> main() async {
  final readings = Stream.fromIterable([1, 1, 2, 2, 2, 3, 1, 1]);
  print('changes only: ${await readings.distinct().toList()}');
}
Output
changes only: [1, 2, 3, 1]
Future<T> firstWhere(bool test(T element), {T orElse()?})

Finds the first element of this stream matching test.

Returns a future that is completed with the first element of this stream for which test returns true.

If no such element is found before this stream is done, and an orElse function is provided, the result of calling orElse becomes the value of the future. If orElse throws, the returned future is completed with that error.

If this stream emits an error before the first matching element, the returned future is completed with that error, and processing stops.

Stops listening to this stream after the first matching element or error has been received.

Internally the method cancels its subscription after the first element that matches the predicate. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this method.

If an error occurs, or if this stream ends without finding a match and with no orElse function provided, the returned future is completed with an error.

Example:

var result = await Stream.fromIterable([1, 3, 4, 9, 12])
    .firstWhere((element) => element % 6 == 0, orElse: () => -1);
print(result); // 12

result = await Stream.fromIterable([1, 2, 3, 4, 5])
    .firstWhere((element) => element % 6 == 0, orElse: () => -1);
print(result); // -1
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([3, 8, 12, 5]);
  print('first > 7: ${await s.firstWhere((n) => n > 7)}');
  final none = await Stream.fromIterable([1, 2]).firstWhere((n) => n > 9, orElse: () => -1);
  print('no match, orElse: $none');
}
Output
first > 7: 8
no match, orElse: -1
lastWheremethod
Future<T> lastWhere(bool test(T element), {T orElse()?})

Finds the last element in this stream matching test.

Returns a future that is completed with the last element of this stream for which test returns true.

If no such element is found before this stream is done, and an orElse function is provided, the result of calling orElse becomes the value of the future. If orElse throws, the returned future is completed with that error.

If this stream emits an error at any point, the returned future is completed with that error, and the subscription is canceled.

A non-error result cannot be provided before this stream is done.

Similar too firstWhere, except that the last matching element is found instead of the first.

Example:

var result = await Stream.fromIterable([1, 3, 4, 7, 12, 24, 32])
    .lastWhere((element) => element % 6 == 0, orElse: () => -1);
print(result); // 24

result = await Stream.fromIterable([1, 3, 4, 7, 12, 24, 32])
    .lastWhere((element) => element % 10 == 0, orElse: () => -1);
print(result); // -1
Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable([3, 8, 12, 5]);
  print('last > 7: ${await s.lastWhere((n) => n > 7)}');
  final none = await Stream.fromIterable([1, 2]).lastWhere((n) => n > 9, orElse: () => 0);
  print('no match, orElse: $none');
}
Output
last > 7: 12
no match, orElse: 0
Future<T> singleWhere(bool test(T element), {T orElse()?})

Finds the single element in this stream matching test.

Returns a future that is completed with the single element of this stream for which test returns true.

If no such element is found before this stream is done, and an orElse function is provided, the result of calling orElse becomes the value of the future. If orElse throws, the returned future is completed with that error.

Only one element may match. If more than one matching element is found an error is thrown, regardless of whether orElse was passed.

If this stream emits an error at any point, the returned future is completed with that error, and the subscription is canceled.

A non-error result cannot be provided before this stream is done.

Similar to lastWhere, except that it is an error if more than one matching element occurs in this stream.

Example:

var result = await Stream.fromIterable([1, 2, 3, 6, 9, 12])
    .singleWhere((element) => element % 4 == 0, orElse: () => -1);
print(result); // 12

result = await Stream.fromIterable([2, 6, 8, 12, 24, 32])
    .singleWhere((element) => element % 9 == 0, orElse: () => -1);
print(result); // -1

result = await Stream.fromIterable([2, 6, 8, 12, 24, 32])
    .singleWhere((element) => element % 6 == 0, orElse: () => -1);
// Throws.
Example
import 'raya:async';

Future<void> main() async {
  print('the only even: ${await Stream.fromIterable([1, 4, 7]).singleWhere((n) => n.isEven)}');
  final two = await Stream.fromIterable([2, 4])
      .singleWhere((n) => n.isEven)
      .then((v) => '$v', onError: (Object e) => 'error: more than one match');
  print(two);
}
Output
the only even: 4
error: more than one match
elementAtmethod
Future<T> elementAt(int index)

Returns the value of the indexth data event of this stream.

Stops listening to this stream after the indexth data event has been received.

Internally the method cancels its subscription after these elements. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this method.

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.

Example
import 'raya:async';

Future<void> main() async {
  final s = Stream.fromIterable(['a', 'b', 'c']);
  print('elementAt(1): ${await s.elementAt(1)}');
  final r = await Stream.fromIterable(['a']).elementAt(5).catchError((Object e) => 'RangeError');
  print('out of range: $r');
}
Output
elementAt(1): b
out of range: RangeError
timeoutmethod
Stream<T> timeout(Duration timeLimit, {void onTimeout(EventSink<T> sink)?})

Creates a new stream with the same events as this stream.

When someone is listening on the returned stream and more than timeLimit passes without any event being emitted by this stream, the onTimeout function is called, which can then emit further events on the returned stream.

The countdown starts when the returned stream is listened to, and is restarted when an event from this stream is emitted, or when listening on the returned stream is paused and resumed. The countdown is stopped when listening on the returned stream is paused or cancelled. No new countdown is started when a countdown completes and the onTimeout function is called, even if events are emitted. If the delay between events of this stream is multiple times timeLimit, at most one timeout will happen between events.

The onTimeout function is called with one argument: an EventSink that allows putting events into the returned stream. This EventSink is only valid during the call to onTimeout. Calling EventSink.close on the sink passed to onTimeout closes the returned stream, and no further events are processed.

If onTimeout is omitted, a timeout will emit a TimeoutException into the error channel of the returned stream. If the call to onTimeout throws, the error is emitted as an error on the returned stream.

The returned stream is a broadcast stream if this stream is. If a broadcast stream is listened to more than once, each subscription will have its individually timer that starts counting on listen, and the subscriptions' timers can be paused individually.

Example:

Future<String> waitTask() async {
  return await Future.delayed(
      const Duration(seconds: 4), () => 'Complete');
}
final stream = Stream<String>.fromFuture(waitTask())
    .timeout(const Duration(seconds: 2), onTimeout: (controller) {
  print('TimeOut occurred');
  controller.close();
});

stream.listen(print, onDone: () => print('Done'));

// Outputs:
// TimeOut occurred
// Done
Example
import 'raya:async';

Future<void> main() async {
  final quiet = StreamController<int>();
  quiet.add(1);
  // No second event arrives; onTimeout closes the stream instead of erroring.
  final got = await quiet.stream
      .timeout(const Duration(milliseconds: 10), onTimeout: (sink) => sink.close())
      .toList();
  print('events before timeout: $got');
  final ctrl = StreamController<int>();
  final r = await ctrl.stream.timeout(const Duration(milliseconds: 5)).toList()
      .catchError((Object e) => <int>[-1]);
  print('without onTimeout: ${r == const [-1] ? 'TimeoutException' : r}');
}
Output
events before timeout: [1]
without onTimeout: [-1]
abstract interface class StreamSubscription<T>

A subscription on events from a Stream.

When you listen on a Stream using Stream.listen, a StreamSubscription object is returned.

The subscription provides events to the listener, and holds the callbacks used to handle the events. The subscription can also be used to unsubscribe from the events, or to temporarily pause the events from the stream.

Example:

final stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i)
    .take(10);

final subscription = stream.listen(print); // A StreamSubscription<int>.

To pause the subscription, use pause.

// Do some work.
subscription.pause();
print(subscription.isPaused); // true

To resume after the pause, use resume.

// Do some work.
subscription.resume();
print(subscription.isPaused); // false

To cancel the subscription, use cancel.

// Do some work.
subscription.cancel();
Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final got = <int>[];
  final sub = c.stream.listen(got.add);
  c.add(1);
  c.add(2);
  await Future.delayed(Duration.zero);
  await sub.cancel(); // stop listening
  c.add(3);
  await Future.delayed(Duration.zero);
  print('received: $got');
  print('hasListener after cancel: ${c.hasListener}');
}
Output
received: [1, 2]
hasListener after cancel: false

Properties

isPausedgetter
bool get isPaused

Whether the StreamSubscription is currently paused.

If there have been more calls to pause than to resume on this stream subscription, the subscription is paused, and this getter returns true.

Returns false if the stream can currently emit events, or if the subscription has completed or been cancelled.

Methods

cancelmethod
Future<void> cancel()

Cancels this subscription.

After this call, the subscription no longer receives events.

The stream may need to shut down the source of events and clean up after the subscription is canceled.

Returns a future that is completed once the stream has finished its cleanup.

Typically, cleanup happens when the stream needs to release resources. For example, a stream might need to close an open file (as an asynchronous operation). If the listener wants to delete the file after having canceled the subscription, it must wait for the cleanup future to complete.

If the cleanup throws, which it really shouldn't, the returned future completes with that error.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final got = <int>[];
  final sub = c.stream.listen(got.add);
  c.add(1);
  c.add(2);
  await Future.delayed(Duration.zero);
  await sub.cancel(); // stop listening
  c.add(3);
  await Future.delayed(Duration.zero);
  print('received: $got');
  print('hasListener after cancel: ${c.hasListener}');
}
Output
received: [1, 2]
hasListener after cancel: false
onDatamethod
void onData(void handleData(T data)?)

Replaces the data event handler of this subscription.

The handleData function is called for each data event of the stream after this function is called. If handleData is null, data events are ignored.

This method replaces the current handler set by the invocation of Stream.listen or by a previous call to onData.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final sub = c.stream.listen((s) => print('first handler: $s'));
  c.add('a');
  await Future.delayed(Duration.zero);
  sub.onData((s) => print('replaced handler: $s')); // swap the data handler
  c.add('b');
  await Future.delayed(Duration.zero);
  await c.close();
}
Output
first handler: a
replaced handler: b
onErrormethod
void onError(Function? handleError)

Replaces the error event handler of this subscription.

The handleError function must be able to be called with either one positional argument, or with two positional arguments where the seconds is always a StackTrace.

The handleError argument may be null, in which case further error events are considered unhandled, and will be reported to Zone.handleUncaughtError.

The provided function is called for all error events from the stream subscription.

This method replaces the current handler set by the invocation of Stream.listen, by calling asFuture, or by a previous call to onError.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final sub = c.stream.listen((n) => print('data $n'));
  sub.onError((Object e) => print('handled error: $e'));
  c.add(1);
  c.addError('sensor offline');
  c.add(2);
  await c.close();
}
Output
data 1
handled error: sensor offline
data 2
onDonemethod
void onDone(void handleDone()?)

Replaces the done event handler of this subscription.

The handleDone function is called when the stream closes. The value may be null, in which case no function is called.

This method replaces the current handler set by the invocation of Stream.listen, by calling asFuture, or by a previous call to onDone.

Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<void>();
  final sub = Stream.fromIterable([1, 2]).listen((n) => print('data $n'));
  sub.onDone(() {
    print('stream finished');
    done.complete();
  });
  await done.future;
}
Output
data 1
data 2
stream finished
pausemethod
void pause([Future<void>? resumeSignal])

Requests that the stream pauses events until further notice.

While paused, the subscription will not fire any events. If it receives events from its source, they will be buffered until the subscription is resumed. For non-broadcast streams, the underlying source is usually informed about the pause, so it can stop generating events until the subscription is resumed.

To avoid buffering events on a broadcast stream, it is better to cancel this subscription, and start to listen again when events are needed, if the intermediate events are not important.

If resumeSignal is provided, the stream subscription will undo the pause when the future completes, as if by a call to resume. If the future completes with an error, the stream will still resume, but the error will be considered unhandled and is passed to Zone.handleUncaughtError.

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. Calls to resume and the completion of a resumeSignal are interchangeable - the pause which was passed a resumeSignal may be ended by a call to resume, and completing the resumeSignal may end a different pause.

It is safe to resume or complete a resumeSignal even when the subscription is not paused, and the resume will have no effect.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final got = <int>[];
  final sub = c.stream.listen(got.add);
  sub.pause(); // events are buffered while paused
  c..add(1)..add(2);
  await Future.delayed(Duration.zero);
  print('while paused: $got, isPaused: ${sub.isPaused}');
  sub.resume();
  await Future.delayed(Duration.zero);
  print('after resume: $got');
  // pause(resumeSignal) resumes when the future completes.
  sub.pause(Future.value());
  c.add(3);
  await Future.delayed(Duration.zero);
  print('auto-resumed: $got');
}
Output
while paused: [], isPaused: true
after resume: [1, 2]
auto-resumed: [1, 2, 3]
resumemethod
void resume()

Resumes after a pause.

This undoes one previous call to pause. When all previously calls to pause have been matched by a calls to resume, possibly through a resumeSignal passed to pause, the stream subscription may emit events again.

It is safe to resume even when the subscription is not paused, and the resume will have no effect.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final sub = c.stream.listen((s) => print('got $s'));
  sub.pause();
  c.add('queued');
  print('paused: ${sub.isPaused}');
  await Future.delayed(Duration.zero);
  sub.resume();
  print('paused: ${sub.isPaused}');
  await c.close();
}
Output
paused: true
paused: false
got queued
asFuturemethod
Future<E> asFuture<E>([E? 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.

If futureValue is omitted, the value null as E is used as a default. If E is not nullable, this will throw immediately when asFuture is called.

Example
import 'raya:async';

Future<void> main() async {
  var sum = 0;
  final sub = Stream.fromIterable([1, 2, 3]).listen((n) => sum += n);
  final r = await sub.asFuture('all done'); // completes on onDone
  print('$r, sum = $sum');
}
Output
all done, sum = 6
abstract interface class EventSink<T> implements Sink<T>

A Sink that supports adding errors.

This makes it suitable for capturing the results of asynchronous computations, which can complete with a value or an error.

The EventSink has been designed to handle asynchronous events from Streams. See, for example, Stream.eventTransformed which uses EventSinks to transform events.

Example
import 'raya:async';

// A sink that keeps every event; any EventSink can feed it.
class Recorder implements EventSink<String> {
  final log = <String>[];
  void add(String e) => log.add('data:$e');
  void addError(Object e, [StackTrace? st]) => log.add('error:$e');
  void close() => log.add('closed');
}

void main() {
  final r = Recorder()
    ..add('a')
    ..addError('oops')
    ..add('b')
    ..close();
  print(r.log);
}
Output
[data:a, error:oops, data:b, closed]

Methods

addmethod
void add(T event)

Adds a data event to the sink.

Must not be called on a closed sink.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final EventSink<int> sink = c.sink;
  sink.add(10);
  sink.add(20);
  sink.close();
  print('events: ${await c.stream.toList()}');
}
Output
events: [10, 20]
addErrormethod
void addError(Object error, [StackTrace? stackTrace])

Adds an error to the sink.

Must not be called on a closed sink.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final EventSink<int> sink = c.sink;
  sink.add(1);
  sink.addError(ArgumentError('bad reading'));
  sink.close();
  c.stream.listen((n) => print('data $n'), onError: (Object e) => print('error $e'),
      onDone: () => print('done'));
  await Future.delayed(Duration.zero);
}
Output
data 1
error Invalid argument(s): bad reading
done
closemethod
void close()

Closes the sink.

Calling this method more than once is allowed, but does nothing.

Neither add nor addError must be called after this method.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  c.stream.listen(print, onDone: () => print('onDone after close'));
  c.sink.add('last event');
  c.sink.close();
  await Future.delayed(Duration.zero);
  print('isClosed: ${c.isClosed}');
}
Output
last event
onDone after close
isClosed: true
class StreamView<T> extends Stream<T>

Stream wrapper that only exposes the Stream interface.

Example
import 'raya:async';

// StreamView hides the controller; callers only get a Stream.
class Ticker extends StreamView<int> {
  Ticker(StreamController<int> c) : super(c.stream);
}

Future<void> main() async {
  final c = StreamController<int>();
  final t = Ticker(c);
  c..add(1)..add(2)..close();
  print('is Stream: ${t is Stream<int>}');
  print('events: ${await t.toList()}');
}
Output
is Stream: true
events: [1, 2]

Constructors

StreamViewconstructor
const StreamView(Stream<T> stream)
Example
import 'raya:async';

// StreamView hides the controller; callers only get a Stream.
class Ticker extends StreamView<int> {
  Ticker(StreamController<int> c) : super(c.stream);
}

Future<void> main() async {
  final c = StreamController<int>();
  final t = Ticker(c);
  c..add(1)..add(2)..close();
  print('is Stream: ${t is Stream<int>}');
  print('events: ${await t.toList()}');
}
Output
is Stream: true
events: [1, 2]

Properties

bool get isBroadcast

Methods

Stream<T> asBroadcastStream({void onListen(StreamSubscription<T> subscription)?, void onCancel(StreamSubscription<T> subscription)?})
Example
import 'raya:async';

Future<void> main() async {
  final v = StreamView(Stream.fromIterable(['x', 'y']));
  final b = v.asBroadcastStream();
  final one = <String>[], two = <String>[];
  b.listen(one.add);
  b.listen(two.add);
  await Future.delayed(Duration.zero);
  print('view broadcast: ${v.isBroadcast}, wrapped broadcast: ${b.isBroadcast}');
  print('listeners got: $one and $two');
}
Output
view broadcast: false, wrapped broadcast: true
listeners got: [x, y] and [x, y]
listenmethod
StreamSubscription<T> listen(void onData(T value)?, {Function? onError, void onDone()?, bool? cancelOnError})
Example
import 'raya:async';

Future<void> main() async {
  final v = StreamView(Stream.fromIterable([1, 2, 3]));
  final done = Completer<void>();
  v.listen((n) => print('event $n'), onDone: done.complete);
  await done.future;
  print('done');
}
Output
event 1
event 2
event 3
done
abstract interface class StreamConsumer<S>

Abstract interface for a "sink" accepting multiple entire streams.

A consumer can accept a number of consecutive streams using addStream, and when no further data need to be added, the close method tells the consumer to complete its work and shut down.

The Stream.pipe accepts a StreamConsumer and will pass the stream to the consumer's addStream method. When that completes, it will call close and then complete its own returned future.

Example
import 'raya:async';

class Summer implements StreamConsumer<int> {
  var total = 0;
  Future addStream(Stream<int> s) => s.forEach((n) => total += n);
  Future close() async => print('closed with total $total');
}

Future<void> main() async {
  final s = Summer();
  await s.addStream(Stream.fromIterable([1, 2, 3]));
  await s.addStream(Stream.fromIterable([10]));
  await s.close();
  final s2 = Summer();
  await Stream.fromIterable([5, 5]).pipe(s2); // pipe uses addStream + close
}
Output
closed with total 16
closed with total 10

Methods

addStreammethod
Future addStream(Stream<S> stream)

Consumes the elements of stream.

Listens on stream and does something for each event.

Returns a future which is completed when the stream is done being added, and the consumer is ready to accept a new stream. No further calls to addStream or close should happen before the returned future has completed.

The consumer may stop listening to the stream after an error, it may consume all the errors and only stop at a done event, or it may be canceled early if the receiver don't want any further events.

If the consumer stops listening because of some error preventing it from continuing, it may report this error in the returned future, otherwise it will just complete the future with null.

Example
import 'raya:async';

class Summer implements StreamConsumer<int> {
  var total = 0;
  Future addStream(Stream<int> s) => s.forEach((n) => total += n);
  Future close() async => print('closed with total $total');
}

Future<void> main() async {
  final s = Summer();
  await s.addStream(Stream.fromIterable([1, 2, 3]));
  await s.addStream(Stream.fromIterable([10]));
  await s.close();
  final s2 = Summer();
  await Stream.fromIterable([5, 5]).pipe(s2); // pipe uses addStream + close
}
Output
closed with total 16
closed with total 10
closemethod
Future close()

Tells the consumer that no further streams will be added.

This allows the consumer to complete any remaining work and release resources that are no longer needed

Returns a future which is completed when the consumer has shut down. If cleaning up can fail, the error may be reported in the returned future, otherwise it completes with null.

Example
import 'raya:async';

class Summer implements StreamConsumer<int> {
  var total = 0;
  Future addStream(Stream<int> s) => s.forEach((n) => total += n);
  Future close() async => print('closed with total $total');
}

Future<void> main() async {
  final s = Summer();
  await s.addStream(Stream.fromIterable([1, 2, 3]));
  await s.addStream(Stream.fromIterable([10]));
  await s.close();
  final s2 = Summer();
  await Stream.fromIterable([5, 5]).pipe(s2); // pipe uses addStream + close
}
Output
closed with total 16
closed with total 10
abstract interface class StreamSink<S> implements EventSink<S>, StreamConsumer<S>

A object that accepts stream events both synchronously and asynchronously.

A StreamSink combines the methods from StreamConsumer and 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.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final StreamSink<String> sink = c.sink;
  final out = c.stream.toList();
  sink.add('one');
  await sink.addStream(Stream.fromIterable(['two', 'three']));
  await sink.close();
  print('events: ${await out}');
  await sink.done;
  print('sink done');
}
Output
events: [one, two, three]
sink done

Properties

donegetter
Future get done

Return a future which is completed when the StreamSink is finished.

If the StreamSink fails with an error, perhaps in response to adding events using add, addError or close, the done future will complete with that error.

Otherwise, the returned future will complete when either:

  • All events have been processed and the sink has been closed, or
  • The sink has otherwise been stopped from handling more events (for example by canceling a stream subscription).

Methods

closemethod
Future close()

Tells the stream sink that no further streams will be added.

This allows the stream sink to complete any remaining work and release resources that are no longer needed

Returns a future which is completed when the stream sink has shut down. If cleaning up can fail, the error may be reported in the returned future, otherwise it completes with null.

Returns the same future as done.

The stream sink may close before the close method is called, either due to an error or because it is itself providing events to someone who has stopped listening. In that case, the done future is completed first, and the close method will return the done future when called.

Unifies StreamConsumer.close and EventSink.close which both mark their object as not expecting any further events.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final StreamSink<String> sink = c.sink;
  final out = c.stream.toList();
  sink.add('one');
  await sink.addStream(Stream.fromIterable(['two', 'three']));
  await sink.close();
  print('events: ${await out}');
  await sink.done;
  print('sink done');
}
Output
events: [one, two, three]
sink done
abstract interface class StreamTransformer<S, T>

Transforms a Stream.

When a stream's Stream.transform method is invoked with a StreamTransformer, the stream calls the bind method on the provided transformer. The resulting stream is then returned from the Stream.transform method.

Conceptually, a transformer is simply a function from Stream to Stream that is encapsulated into a class.

It is good practice to write transformers that can be used multiple times.

All other transforming methods on Stream, such as Stream.map, Stream.where or Stream.expand can be implemented using Stream.transform. A StreamTransformer is thus very powerful but often also a bit more complicated to use.

The StreamTransformer.fromHandlers constructor allows passing separate callbacks to react to events, errors, and the end of the stream. The StreamTransformer.fromBind constructor creates a StreamTransformer whose bind method is implemented by calling the function passed to the constructor.

Example
import 'raya:async';

Future<void> main() async {
  final splitter = StreamTransformer<String, String>.fromHandlers(
    handleData: (line, sink) => line.split(' ').forEach(sink.add),
  );
  final words = Stream.fromIterable(['a b', 'c d e']).transform(splitter);
  print('words: ${await words.toList()}');
}
Output
words: [a, b, c, d, e]

Constructors

const factory StreamTransformer(StreamSubscription<T> onListen(Stream<S> stream, bool cancelOnError)) = _StreamSubscriptionTransformer<S, T>

Creates a StreamTransformer based on the given onListen callback.

The returned stream transformer uses the provided onListen callback when a transformed stream is listened to. At that time, the callback receives the input stream (the one passed to bind) and a boolean flag cancelOnError to create a StreamSubscription.

If the transformed stream is a broadcast stream, so is the stream returned by the StreamTransformer.bind method by this transformer.

If the transformed stream is listened to multiple times, the onListen callback is called again for each new Stream.listen call. This happens whether the stream is a broadcast stream or not, but the call will usually fail for non-broadcast streams.

The onListen callback does not receive the handlers that were passed to Stream.listen. These are automatically set after the call to the onListen callback (using StreamSubscription.onData, StreamSubscription.onError and StreamSubscription.onDone).

Most commonly, an onListen callback will first call Stream.listen on the provided stream (with the corresponding cancelOnError flag), and then return a new StreamSubscription.

There are two common ways to create a StreamSubscription:

  1. By allocating a StreamController and to return the result of listening to its stream. It's important to forward pause, resume and cancel events (unless the transformer intentionally wants to change this behavior).
  2. By creating a new class that implements StreamSubscription. Note that the subscription should run callbacks in the Zone the stream was listened to (see Zone and Zone.bindCallback).

Example:

/// Starts listening to [input] and duplicates all non-error events.
StreamSubscription<int> _onListen(Stream<int> input, bool cancelOnError) {
  // Create the result controller.
  // Using `sync` is correct here, since only async events are forwarded.
  var controller = StreamController<int>(sync: true);
  controller.onListen = () {
    var subscription = input.listen((data) {
      // Duplicate the data.
      controller.add(data);
      controller.add(data);
    },
        onError: controller.addError,
        onDone: controller.close,
        cancelOnError: cancelOnError);
    // Controller forwards pause, resume and cancel events.
    controller
      ..onPause = subscription.pause
      ..onResume = subscription.resume
      ..onCancel = subscription.cancel;
  };
  // Return a new [StreamSubscription] by listening to the controller's
  // stream.
  return controller.stream.listen(null);
}

// Instantiate a transformer:
var duplicator = const StreamTransformer<int, int>(_onListen);

// Use as follows:
intStream.transform(duplicator);
Example
import 'raya:async';

Future<void> main() async {
  // The onListen form: build the output subscription yourself.
  final doubler = StreamTransformer<int, int>((input, cancelOnError) {
    final out = StreamController<int>(sync: true);
    out.onListen = () {
      final sub = input.listen((n) => out.add(n * 2), onDone: out.close);
      out.onCancel = sub.cancel;
    };
    return out.stream.listen(null);
  });
  print('doubled: ${await Stream.fromIterable([1, 2, 3]).transform(doubler).toList()}');
}
Output
doubled: [2, 4, 6]
factory StreamTransformer.fromHandlers({void handleData(S data, EventSink<T> sink)?, void handleError(Object error, StackTrace stackTrace, EventSink<T> sink)?, void handleDone(EventSink<T> sink)?}) = _StreamHandlerTransformer<S, T>

Creates a StreamTransformer that delegates events to the given functions.

Example use of a duplicating transformer:

stringStream.transform(StreamTransformer<String, String>.fromHandlers(
    handleData: (String value, EventSink<String> sink) {
      sink.add(value);
      sink.add(value);  // Duplicate the incoming events.
    }));

When a transformed stream returned from a call to bind is listened to, the source stream is listened to, and a handler function is called for each event of the source stream.

The handlers are invoked with the event data and with a sink that can be used to emit events on the transformed stream.

The handleData handler is invoked for data events on the source stream. If handleData was omitted, data events are added directly to the created stream, as if calling EventSink.add on the sink with the event value. If handleData is omitted the source stream event type, S, must be a subtype of the transformed stream event type T.

The handleError handler is invoked for each error of the source stream. If handleError is omitted, errors are forwarded directly to the transformed stream, as if calling EventSink.addError with the error and stack trace.

The handleDone handler is invoked when the source stream closes, as signaled by sending a done event. The done handler takes no event value, but can still send other events before calling EventSink.close. If handleDone is omitted, a done event on the source stream closes the transformed stream.

If any handler calls EventSink.close on the provided sink, the transformed sink closes and the source stream subscription is cancelled. No further events can be added to the sink by that handler, and no further source stream events will occur.

The sink provided to the event handlers must only be used during the call to that handler. It must not be stored and used at a later time.

Transformers created this way should be stateless. They should not retain state between invocations of handlers, because the same transformer, and therefore the same handlers, may be used on multiple streams, or on streams which can be listened to more than once. To create per-stream handlers, StreamTransformer.fromBind could be used to create a new StreamTransformer.fromHandlers per stream to transform.

var controller = StreamController<String>.broadcast();
controller.onListen = () {
  scheduleMicrotask(() {
    controller.addError("Bad");
    controller.addError("Worse");
    controller.addError("Worst");
  });
};
var sharedState = 0;
var transformedStream = controller.stream.transform(
    StreamTransformer<String>.fromHandlers(
        handleError: (error, stackTrace, sink) {
  sharedState++; // Increment shared error-counter.
  sink.add("Error $sharedState: $error");
}));

transformedStream.listen(print);
transformedStream.listen(print); // Listen twice.
// Listening twice to the same stream makes the transformer share the same
// state. Instead of having "Error 1: Bad", "Error 2: Worse",
// "Error 3: Worst" as output (each twice for the separate subscriptions),
// this program emits:
// Error 1: Bad
// Error 2: Bad
// Error 3: Worse
// Error 4: Worse
// Error 5: Worst
// Error 6: Worst
Example
import 'raya:async';

Future<void> main() async {
  final parse = StreamTransformer<String, int>.fromHandlers(
    handleData: (s, sink) {
      final n = int.tryParse(s);
      n == null ? sink.addError(FormatException('not a number', s)) : sink.add(n);
    },
    handleError: (e, st, sink) => sink.add(-1),
    handleDone: (sink) {
      sink.add(0); // a trailer event
      sink.close();
    },
  );
  final src = StreamController<String>();
  final out = src.stream.transform(parse).handleError((Object e) => print('bad: $e')).toList();
  src..add('4')..add('x')..addError('upstream')..add('7')..close();
  print('parsed: ${await out}');
}
Output
bad: FormatException: not a number
x
parsed: [4, -1, 7, 0]
factory StreamTransformer.fromBind(Stream<T> Function(Stream<S>) bind) = _StreamBindTransformer<S, T>

Creates a StreamTransformer based on a bind callback.

The returned stream transformer uses the bind argument to implement the StreamTransformer.bind API and can be used when the transformation is available as a stream-to-stream function.

final splitDecoded = StreamTransformer<List<int>, String>.fromBind(
    (stream) => stream.transform(utf8.decoder).transform(LineSplitter()));
Example
import 'raya:async';

Future<void> main() async {
  final trimEmpty = StreamTransformer<String, String>.fromBind(
      (s) => s.map((l) => l.trim()).where((l) => l.isNotEmpty));
  final lines = Stream.fromIterable(['  one ', '', ' two', '   ']);
  print('lines: ${await lines.transform(trimEmpty).toList()}');
}
Output
lines: [one, two]

Static

castFromstaticmethod
static StreamTransformer<TS, TT> castFrom<SS, ST, TS, TT>(StreamTransformer<SS, ST> source)

Adapts source to be a StreamTransformer<TS, TT>.

This allows source to be used at the new type, but at run-time it must satisfy the requirements of both the new type and its original type.

Data events passed into the returned transformer must also be instances of SS, and data events produced by source for those events must also be instances of TT.

Example
import 'raya:async';

Future<void> main() async {
  final StreamTransformer<Object, Object> t = StreamTransformer.fromBind((s) => s.map((o) => '<$o>'));
  final typed = StreamTransformer.castFrom<Object, Object, int, String>(t);
  print(await Stream.fromIterable([1, 2]).transform(typed).toList());
}
Output
[<1>, <2>]

Methods

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

Transforms the provided stream.

Returns a new stream with events that are computed from events of the provided stream.

The StreamTransformer interface is completely generic, so it cannot say what subclasses do. Each StreamTransformer should document clearly how it transforms the stream (on the class or variable used to access the transformer), as well as any differences from the following typical behavior:

  • When the returned stream is listened to, it starts listening to the input stream.
  • Subscriptions of the returned stream forward (in a reasonable time) a StreamSubscription.pause call to the subscription of the input stream.
  • Similarly, canceling a subscription of the returned stream eventually (in reasonable time) cancels the subscription of the input stream.

"Reasonable time" depends on the transformer and stream. Some transformers, like a "timeout" transformer, might make these operations depend on a duration. Others might not delay them at all, or just by a microtask.

Transformers are free to handle errors in any way. A transformer implementation may choose to propagate errors, or convert them to other events, or ignore them completely, but if errors are ignored, it should be documented explicitly.

Example
import 'raya:async';

Future<void> main() async {
  final squarer = StreamTransformer<int, int>.fromBind((s) => s.map((n) => n * n));
  // bind is what Stream.transform calls.
  final a = await squarer.bind(Stream.fromIterable([1, 2, 3])).toList();
  final b = await Stream.fromIterable([1, 2, 3]).transform(squarer).toList();
  print('bind: $a, transform: $b');
}
Output
bind: [1, 4, 9], transform: [1, 4, 9]
castmethod
StreamTransformer<RS, RT> cast<RS, RT>()

Provides a StreamTransformer<RS, RT> view of this stream transformer.

The resulting transformer will check at run-time that all data events of the stream it transforms are actually instances of S, and it will check that all data events produced by this transformer are actually instances of RT.

Example
import 'raya:async';

Future<void> main() async {
  final StreamTransformer<num, num> half = StreamTransformer.fromBind((s) => s.map((n) => n / 2));
  final StreamTransformer<int, double> typed = half.cast<int, double>();
  print(await Stream.fromIterable([2, 5]).transform(typed).toList());
}
Output
[1.0, 2.5]
abstract class StreamTransformerBase<S, T> implements StreamTransformer<S, T>

Base class for implementing StreamTransformer.

Contains default implementations of every method except bind.

Example
import 'raya:async';

class Prefix extends StreamTransformerBase<String, String> {
  final String p;
  const Prefix(this.p);
  @override
  Stream<String> bind(Stream<String> s) => s.map((x) => '$p$x');
}

Future<void> main() async {
  final out = Stream.fromIterable(['a', 'b']).transform(const Prefix('> '));
  print(await out.toList());
}
Output
[> a, > b]

Constructors

const StreamTransformerBase()
Example
import 'raya:async';

class Prefix extends StreamTransformerBase<String, String> {
  final String p;
  const Prefix(this.p);
  @override
  Stream<String> bind(Stream<String> s) => s.map((x) => '$p$x');
}

Future<void> main() async {
  final out = Stream.fromIterable(['a', 'b']).transform(const Prefix('> '));
  print(await out.toList());
}
Output
[> a, > b]

Methods

castmethod
StreamTransformer<RS, RT> cast<RS, RT>()
Example
import 'raya:async';

class Negate extends StreamTransformerBase<num, num> {
  const Negate();
  @override
  Stream<num> bind(Stream<num> s) => s.map((n) => -n);
}

Future<void> main() async {
  final StreamTransformer<int, int> t = const Negate().cast<int, int>();
  print('negated: ${await Stream.fromIterable([1, 2, 3]).transform(t).toList()}');
}
Output
negated: [-1, -2, -3]
abstract interface class StreamIterator<T>

An Iterator-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.

The stream may be paused between calls to moveNext.

The current value must only be used after a future returned by moveNext has completed with true, and only until moveNext is called again.

Example
import 'raya:async';

Future<void> main() async {
  final it = StreamIterator(Stream.fromIterable(['header', 'a', 'b', 'c']));
  // Pull events one at a time, at your own pace.
  if (await it.moveNext()) print('header: ${it.current}');
  final rest = <String>[];
  while (await it.moveNext()) {
    rest.add(it.current);
  }
  print('rest: $rest');
}
Output
header: header
rest: [a, b, c]

Constructors

factory StreamIterator(Stream<T> stream)

Create a StreamIterator on stream.

Example
import 'raya:async';

Future<void> main() async {
  final it = StreamIterator(Stream.fromIterable(['header', 'a', 'b', 'c']));
  // Pull events one at a time, at your own pace.
  if (await it.moveNext()) print('header: ${it.current}');
  final rest = <String>[];
  while (await it.moveNext()) {
    rest.add(it.current);
  }
  print('rest: $rest');
}
Output
header: header
rest: [a, b, c]

Properties

currentgetter
T get current

The current value of the stream.

When a moveNext call completes with true, the current field holds the most recent event of the stream, and it stays like that until the next call to moveNext. This value must only be read after a call to moveNext has completed with true, and only until the moveNext is called again.

If the StreamIterator has not yet been moved to the first element (moveNext has not been called and completed yet), or if the StreamIterator has been moved past the last element (moveNext has returned false), then current is unspecified. A StreamIterator may either throw or return an iterator-specific default value in that case.

Methods

moveNextmethod
Future<bool> moveNext()

Wait for the next stream value to be available.

Returns a future which will complete with either true or false. Completing with true means that another event has been received and can be read as current. Completing with false means that the stream iteration is done and no further events will ever be available. The future may complete with an error, if the stream produces an error, which also ends iteration.

The function must not be called again until the future returned by a previous call is completed.

Example
import 'raya:async';

Future<void> main() async {
  final it = StreamIterator(Stream.fromIterable(['header', 'a', 'b', 'c']));
  // Pull events one at a time, at your own pace.
  if (await it.moveNext()) print('header: ${it.current}');
  final rest = <String>[];
  while (await it.moveNext()) {
    rest.add(it.current);
  }
  print('rest: $rest');
}
Output
header: header
rest: [a, b, c]
cancelmethod
Future 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 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.

If moveNext has been called when the iterator is canceled, its returned future will complete with false as value, as will all further calls to moveNext.

Returns a future which completes when the cancellation is complete. This can be an already completed future if the cancellation happens synchronously.

Example
import 'raya:async';

Future<void> main() async {
  var cancelled = false;
  final c = StreamController<int>(onCancel: () => cancelled = true);
  for (var i = 1; i <= 5; i++) c.add(i);
  final it = StreamIterator(c.stream);
  await it.moveNext();
  print('took: ${it.current}');
  await it.cancel(); // stop early; the source sees the cancel
  print('source cancelled: $cancelled');
  print('moveNext after cancel: ${await it.moveNext()}');
}
Output
took: 1
source cancelled: true
moveNext after cancel: false
abstract interface class MultiStreamController<T> implements StreamController<T>

An enhanced stream controller provided by Stream.multi.

Acts like a normal asynchronous controller, but also allows adding events synchronously. As with any synchronous event delivery, the sender should be very careful to not deliver events at times when a new listener might not be ready to receive them. That usually means only delivering events synchronously in response to other asynchronous events, because that is a time when an asynchronous event could happen.

Example
import 'raya:async';

Future<void> main() async {
  final s = Stream<int>.multi((MultiStreamController<int> c) {
    c.add(1);
    c.addSync(2);
    c.close();
  });
  print('A: ${await s.toList()}');
  print('B: ${await s.toList()}');
}
Output
A: [1, 2]
B: [1, 2]

Methods

addSyncmethod
void addSync(T value)

Adds and delivers an event.

Adds an event like add and attempts to deliver it immediately. Delivery can be delayed if other previously added events are still pending delivery, if the subscription is paused, or if the subscription isn't listening yet.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final s = Stream<int>.multi((c) {
    c.addSync(1); // delivered immediately, before the next line runs
    log.add('after addSync');
    c.add(2); // delivered later
    log.add('after add');
    c.close();
  });
  await s.forEach((n) => log.add('got $n'));
  print(log);
}
Output
[after addSync, after add, got 1, got 2]
void addErrorSync(Object error, [StackTrace? stackTrace])

Adds and delivers an error event.

Adds an error like addError and attempts to deliver it immediately. Delivery can be delayed if other previously added events are still pending delivery, if the subscription is paused, or if the subscription isn't listening yet.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final s = Stream<int>.multi((c) {
    c.addErrorSync('bad frame');
    log.add('after addErrorSync');
    c.closeSync();
  });
  final done = Completer<void>();
  s.listen((n) {}, onError: (Object e) => log.add('error: $e'), onDone: done.complete);
  await done.future;
  print(log);
}
Output
[after addErrorSync, error: bad frame]
closeSyncmethod
void closeSync()

Closes the controller and delivers a done event.

Closes the controller like close and attempts to deliver a "done" event immediately. Delivery can be delayed if other previously added events are still pending delivery, if the subscription is paused, or if the subscription isn't listening yet. If it's necessary to know whether the "done" event has been delivered, done future will complete when that has happened.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final s = Stream<String>.multi((c) {
    c.addSync('only');
    c.closeSync(); // onDone runs right here
    log.add('after closeSync');
  });
  s.listen((v) => log.add('data $v'), onDone: () => log.add('done'));
  await Future.delayed(Duration.zero);
  print(log);
}
Output
[after closeSync, data only, done]
abstract interface class StreamController<T> implements StreamSink<T>

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.

Example:

final streamController = StreamController(
  onPause: () => print('Paused'),
  onResume: () => print('Resumed'),
  onCancel: () => print('Cancelled'),
  onListen: () => print('Listens'),
);

streamController.stream.listen(
  (event) => print('Event: $event'),
  onDone: () => print('Done'),
  onError: (error) => print(error),
);

To check whether there is a subscriber on the stream, use hasListener.

var hasListener = streamController.hasListener; // true

To send data events to the stream, use add or addStream.

streamController.add(999);
final stream = Stream<int>.periodic(
    const Duration(milliseconds: 200), (count) => count * count).take(4);
await streamController.addStream(stream);

To send an error event to the stream, use addError or addStream.

streamController.addError(Exception('Issue 101'));
await streamController.addStream(Stream.error(Exception('Issue 404')));

To check whether the stream is closed, use isClosed.

var isClosed = streamController.isClosed; // false

To close the stream, use close.

await streamController.close();
isClosed = streamController.isClosed; // true
Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final collected = c.stream.map((s) => s.toUpperCase()).toList();
  c.add('one');
  c.add('two');
  c.add('three');
  await c.close();
  print('collected: ${await collected}');
}
Output
collected: [ONE, TWO, THREE]

Constructors

factory StreamController({void onListen()?, void onPause()?, void onResume()?, FutureOr<void> onCancel()?, bool sync = false})

A controller with a stream that supports only one single subscriber.

If sync is true, the returned stream controller is a SynchronousStreamController, and must be used with the care and attention necessary to not break the Stream contract. If in doubt, use the non-sync version.

Using an asynchronous controller will never give the wrong behavior, but using a synchronous controller incorrectly can cause otherwise correct programs to break.

A synchronous controller is only intended for optimizing event propagation when one asynchronous event immediately triggers another. It should not be used unless the calls to add or addError are guaranteed to occur in places where it won't break Stream invariants.

Use synchronous controllers only to forward (potentially transformed) events from another stream or a future.

A Stream should be inert until a subscriber starts listening on it (using the onListen callback to start producing events). Streams should not leak resources (like websockets) when no user ever listens on the stream.

The controller buffers all incoming events until a subscriber is registered, but this feature should only be used in rare circumstances.

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 onCancel needs to perform an asynchronous operation, onCancel should return a future that completes when the cancel operation is done.

If the stream is canceled before the controller needs data the onResume call might not be executed.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final c = StreamController<int>(
    onListen: () => log.add('listen'),
    onPause: () => log.add('pause'),
    onResume: () => log.add('resume'),
    onCancel: () => log.add('cancel'),
  );
  final sub = c.stream.listen((n) => log.add('data $n'));
  c.add(1);
  await Future.delayed(Duration.zero);
  sub.pause();
  sub.resume();
  await sub.cancel();
  print(log);
}
Output
[listen, data 1, pause, resume, cancel]
factory StreamController.broadcast({void onListen()?, void onCancel()?, bool sync = false})

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.

A Stream should be inert until a subscriber starts listening on it (using the onListen callback to start producing events). Streams should not leak resources (like websockets) when no user ever listens on the stream.

Broadcast streams do not buffer events when there is no listener.

The controller distributes any events to all currently subscribed listeners at the time when add, addError or close is called. It is not allowed to call add, addError, or close before a previous call has returned. The controller does not have any internal queue of events, and if there are no listeners at the time the event or error is added, it will just be dropped.

Each listener subscription is handled independently, and if one pauses, only the pausing listener is affected. A paused listener will buffer events internally until unpaused or canceled.

If sync is true, events may be fired directly by the stream's subscriptions during an add, addError or close call. The returned stream controller is a SynchronousStreamController, and must be used with the care and attention necessary to not break the Stream contract. See Completer.sync for some explanations on when a synchronous dispatching can be used. If in doubt, keep the controller non-sync.

If sync is false, the event will always be fired at a later time, after the code adding the event has completed. In that case, 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. Each subscription handles the events individually. 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 receive 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.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>.broadcast();
  final a = c.stream.toList();
  final b = c.stream.where((x) => x > 1).toList();
  for (final x in [1, 2, 3]) c.add(x);
  await c.close();
  print('listener a: ${await a}');
  print('listener b: ${await b}');
}
Output
listener a: [1, 2, 3]
listener b: [2, 3]

Properties

streamgetter
Stream<T> get stream

The stream that this controller is controlling.

abstract void Function()? onListen

The callback which is called when the stream is listened to.

May be set to null, in which case no callback will happen.

onPausefield
abstract void Function()? onPause

The callback which is called when the stream is paused.

May be set to null, in which case no callback will happen.

Pause related callbacks are not supported on broadcast stream controllers.

abstract void Function()? onResume

The callback which is called when the stream is resumed.

May be set to null, in which case no callback will happen.

Pause related callbacks are not supported on broadcast stream controllers.

abstract FutureOr<void> Function()? onCancel

The callback which is called when the stream is canceled.

May be set to null, in which case no callback will happen.

sinkgetter
StreamSink<T> get sink

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

isClosedgetter
bool get isClosed

Whether the stream controller is closed for adding more events.

The controller becomes closed by calling the close method. New events cannot be added, by calling add or addError, to a closed controller.

If the controller is closed, the "done" event might not have been delivered yet, but it has been scheduled, and it is too late to add more events.

isPausedgetter
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 subscriptions, if any, and let the subscriptions handle their own pausing and buffering.

bool get hasListener

Whether there is a subscriber on the Stream.

donegetter
Future get done

A future which is completed when the stream controller is done sending events.

This happens either when the done event has been sent, or if the subscriber on a single-subscription stream is canceled.

A stream controller will not complete the returned future until all listeners present when the done event is sent have stopped listening. A listener will stop listening if it is cancelled, or if it has handled the done event. A paused listener will not process the done even until it is resumed, so completion of the returned Future will be delayed until all paused listeners have been resumed or cancelled.

If there is no listener on a non-broadcast stream, or the listener pauses and never resumes, the done event will not be sent and this future will never complete.

Methods

addmethod
void add(T event)

Sends a data event.

Listeners receive this event in a later microtask.

Note that a synchronous controller (created by passing true to the sync parameter of the StreamController constructor) delivers events immediately. Since this behavior violates the contract mentioned here, synchronous controllers should only be used as described in the documentation to ensure that the delivered events always appear as if they were delivered in a separate microtask.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<String>();
  final events = c.stream.toList();
  c.add('a');
  c.add('b');
  await c.close();
  print('events: ${await events}');
  try {
    c.add('late');
  } on StateError catch (e) {
    print('add after close: ${e.message}');
  }
}
Output
events: [a, b]
add after close: Cannot add event after closing
addErrormethod
void addError(Object error, [StackTrace? stackTrace])

Sends or enqueues an error event.

Listeners receive this event at a later microtask. This behavior can be overridden by using sync controllers. Note, however, that sync controllers have to satisfy the preconditions mentioned in the documentation of the constructors.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  c.stream.listen((n) => print('data $n'), onError: (Object e) => print('error $e'));
  c.add(1);
  c.addError(RangeError('value too large'));
  c.add(2);
  await c.close();
}
Output
data 1
error RangeError: value too large
data 2
closemethod
Future close()

Closes the stream.

No further events can be added to a closed stream.

The returned future is the same future provided by done. It is completed when the stream listeners is done sending events, This happens either when the done event has been sent, or when the subscriber on a single-subscription stream is canceled.

A stream controller will not complete the returned future until all listeners present when the done event is sent have stopped listening. A listener will stop listening if it is cancelled, or if it has handled the done event. A paused listener will not process the done even until it is resumed, so completion of the returned Future will be delayed until all paused listeners have been resumed or cancelled.

If no one listens to a non-broadcast stream, or the listener pauses and never resumes, the done event will not be sent and this future will never complete.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  c.stream.listen((n) => print('data $n'), onDone: () => print('listener: done'));
  c.add(1);
  print('isClosed before: ${c.isClosed}');
  await c.close(); // completes when the done event is delivered
  print('isClosed after: ${c.isClosed}');
}
Output
isClosed before: false
data 1
listener: done
isClosed after: true
addStreammethod
Future addStream(Stream<T> source, {bool? cancelOnError})

Receives events from source and puts them into this controller's stream.

Returns a future which completes when the source stream is done.

Events must not be added directly to this controller using add, addError, close or addStream, until the returned future is complete.

Data and error events are forwarded to this controller's stream. A done event on the source will end the addStream operation and complete the returned future.

If cancelOnError is true, only the first error on source is forwarded to the controller's stream, and the addStream ends after this. If cancelOnError is false, all errors are forwarded and only a done event will end the addStream. If cancelOnError is omitted or null, it defaults to false.

Example
import 'raya:async';

Future<void> main() async {
  final c = StreamController<int>();
  final all = c.stream.toList();
  c.add(0);
  await c.addStream(Stream.fromIterable([1, 2, 3])); // forwards every event
  c.add(4);
  await c.close();
  print('merged: ${await all}');
}
Output
merged: [0, 1, 2, 3, 4]
abstract interface class SynchronousStreamController<T> implements StreamController<T>

A stream controller that delivers its events synchronously.

A synchronous stream controller is intended for cases where an already asynchronous event triggers an event on a stream.

Instead of adding the event to the stream in a later microtask, causing extra latency, the event is instead fired immediately by the synchronous stream controller, as if the stream event was the current event or microtask.

The synchronous stream controller can be used to break the contract on Stream, and it must be used carefully to avoid doing so.

The only advantage to using a SynchronousStreamController over a normal StreamController is the improved latency. Only use the synchronous version if the improvement is significant, and if its use is safe. Otherwise just use a normal stream controller, which will always have the correct behavior for a Stream, and won't accidentally break other code.

Adding events to a synchronous controller should only happen as the very last part of the handling of the original event. At that point, adding an event to the stream is equivalent to returning to the event loop and adding the event in the next microtask.

Each listener callback will be run as if it was a top-level event or microtask. This means that if it throws, the error will be reported as uncaught as soon as possible. This is one reason to add the event as the last thing in the original event handler – any action done after adding the event will delay the report of errors in the event listener callbacks.

If an event is added in a setting that isn't known to be another event, it may cause the stream's listener to get that event before the listener is ready to handle it. We promise that after calling Stream.listen, you won't get any events until the code doing the listen has completed. Calling add in response to a function call of unknown origin may break that promise.

An onListen callback from the controller is not an asynchronous event, and adding events to the controller in the onListen callback is always wrong. The events will be delivered before the listener has even received the subscription yet.

The synchronous broadcast stream controller also has a restrictions that a normal stream controller does not: The add, addError, close and addStream methods must not be called while an event is being delivered. That is, if a callback on a subscription on the controller's stream causes a call to any of the functions above, the call will fail. A broadcast stream may have more than one listener, and if an event is added synchronously while another is being also in the process of being added, the latter event might reach some listeners before the former. To prevent that, an event cannot be added while a previous event is being fired. This guarantees that an event is fully delivered when the first add, addError or close returns, and further events will be delivered in the correct order.

This still only guarantees that the event is delivered to the subscription. If the subscription is paused, the actual callback may still happen later, and the event will instead be buffered by the subscription. Barring pausing, and the following buffered events that haven't been delivered yet, callbacks will be called synchronously when an event is added.

Adding an event to a synchronous non-broadcast stream controller while another event is in progress may cause the second event to be delayed and not be delivered synchronously, and until that event is delivered, the controller will not act synchronously.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final c = StreamController<int>(sync: true);
  print('is synchronous: ${c is SynchronousStreamController<int>}');
  c.stream.listen((n) => log.add('got $n'));
  c.add(1);
  log.add('after add'); // the listener already ran
  print(log);
}
Output
is synchronous: true
[got 1, after add]

Methods

addmethod
void add(T data)

Adds event to the controller's stream.

As StreamController.add, but must not be called while an event is being added by add, addError or close.

Example
import 'raya:async';

Future<void> main() async {
  final log = <String>[];
  final c = StreamController<int>(sync: true);
  print('is synchronous: ${c is SynchronousStreamController<int>}');
  c.stream.listen((n) => log.add('got $n'));
  c.add(1);
  log.add('after add'); // the listener already ran
  print(log);
}
Output
is synchronous: true
[got 1, after add]
addErrormethod
void addError(Object error, [StackTrace? stackTrace])

Adds error to the controller's stream.

As StreamController.addError, but must not be called while an event is being added by add, addError or close.

Example
import 'raya:async';

void main() {
  final log = <String>[];
  final c = StreamController<int>(sync: true);
  c.stream.listen((n) {}, onError: (Object e) => log.add('error $e'));
  c.addError('disk full');
  log.add('after addError');
  print(log);
}
Output
[error disk full, after addError]
closemethod
Future close()

Closes the controller's stream.

As StreamController.close, but must not be called while an event is being added by add, addError or close.

Example
import 'raya:async';

void main() {
  final log = <String>[];
  final c = StreamController<int>(sync: true);
  c.stream.listen((n) => log.add('got $n'), onDone: () => log.add('done'));
  c.add(7);
  c.close();
  log.add('after close');
  print(log);
}
Output
[got 7, done, after close]
class

Timer

abstract interface class Timer

A countdown 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 Duration.zero. If the duration is statically known to be 0, consider using run.

void main() {
  Timer(const Duration(seconds: 5), handleTimeout);
}

void handleTimeout() {  // callback function
  // Do some work.
}

Note: If Raya code using Timer is compiled to JavaScript, the finest granularity available in the browser is 4 milliseconds.

See also:

Example
import 'raya:async';

void main() {
  var n = 0;
  Timer.periodic(const Duration(milliseconds: 5), (t) {
    n++;
    print('tick $n');
    if (n == 3) {
      t.cancel();
      print('cancelled, isActive ${t.isActive}');
    }
  });
  Timer(Duration.zero, () => print('a one-shot timer'));
}
Output
a one-shot timer
tick 1
tick 2
tick 3
cancelled, isActive false

Constructors

Timerfactory
factory Timer(Duration duration, void Function() callback)

Creates a new timer.

The callback function is invoked after the given duration.

Example:

final timer =
    Timer(const Duration(seconds: 5), () => print('Timer finished'));
// Outputs after 5 seconds: "Timer finished".
Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<void>();
  final order = <String>[];
  Timer(const Duration(milliseconds: 20), () => order.add('20 ms timer'));
  Timer(const Duration(milliseconds: 5), () => order.add('5 ms timer'));
  Timer(const Duration(milliseconds: 40), done.complete);
  await done.future;
  print('fired in order: $order');
}
Output
fired in order: [5 ms timer, 20 ms timer]
factory Timer.periodic(Duration duration, void callback(Timer timer))

Creates a new repeating timer.

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

The exact timing depends on the underlying timer implementation. No more than n callbacks will be made in duration * n time, but the time between two consecutive callbacks can be shorter and longer than duration.

In particular, an implementation may schedule the next callback, e.g. a duration after either when the previous callback ended, when the previous callback started, or when the previous callback was scheduled for - even if the actual callback was delayed.

A negative duration is treated the same as Duration.zero.

Example:

var counter = 3;
Timer.periodic(const Duration(seconds: 2), (timer) {
  print(timer.tick);
  counter--;
  if (counter == 0) {
    print('Cancel timer');
    timer.cancel();
  }
});
// Outputs:
// 1
// 2
// 3
// "Cancel timer"
Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<void>();
  Timer.periodic(const Duration(milliseconds: 5), (t) {
    print('tick ${t.tick}');
    if (t.tick == 3) {
      t.cancel();
      done.complete();
    }
  });
  await done.future;
  print('stopped');
}
Output
tick 1
tick 2
tick 3
stopped

Static

runstaticmethod
static void run(void Function() callback)

Runs the given callback asynchronously as soon as possible.

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

Example:

Timer.run(() => print('timer run'));
Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  Timer.run(() => order.add('Timer.run'));
  scheduleMicrotask(() => order.add('microtask'));
  order.add('sync');
  await Future.delayed(const Duration(milliseconds: 1));
  print(order);
}
Output
[sync, microtask, Timer.run]

Properties

tickgetter
int get tick

The number of durations preceding the most recent timer event.

The value starts at zero and is incremented each time a timer event occurs, so each callback will see a larger value than the previous one.

If a periodic timer with a non-zero duration is delayed too much, so more than one tick should have happened, all but the last tick in the past are considered "missed", and no callback is invoked for them. The tick count reflects the number of durations that have passed and not the number of callback invocations that have happened.

Example:

final stopwatch = Stopwatch()..start();
Timer.periodic(const Duration(seconds: 1), (timer) {
  print(timer.tick);
  if (timer.tick == 1) {
    while (stopwatch.elapsedMilliseconds < 4500) {
      // Run uninterrupted for another 3.5 seconds!
      // The latest due tick after that is the 4-second tick.
    }
  } else {
    timer.cancel();
  }
});
// Outputs:
// 1
// 4
isActivegetter
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.

Methods

cancelmethod
void cancel()

Cancels the timer.

Once a Timer has been canceled, the callback function will not be called by the timer. Calling cancel more than once on a Timer is allowed, and will have no further effect.

Example:

final timer =
    Timer(const Duration(seconds: 5), () => print('Timer finished'));
// Cancel timer, callback never called.
timer.cancel();
Example
import 'raya:async';

Future<void> main() async {
  var fired = false;
  final t = Timer(const Duration(milliseconds: 5), () => fired = true);
  print('isActive: ${t.isActive}');
  t.cancel();
  print('isActive after cancel: ${t.isActive}');
  await Future.delayed(const Duration(milliseconds: 15));
  print('fired: $fired');
}
Output
isActive: true
isActive after cancel: false
fired: false
class

Zone

abstract final class Zone

A zone represents an environment that remains stable across asynchronous calls.

All code is executed in the context of a zone, available to the code as Zone.current. The initial main function runs in the context of the default zone (Zone.root). Code can be run in a different zone using either runZoned or runZonedGuarded to create a new zone and run code in it, or Zone.run to run code in the context of an existing zone which may have been created earlier using Zone.fork.

Developers can create a new zone that overrides some of the functionality of an existing zone. For example, custom zones can replace or modify the behavior of print, timers, microtasks or how uncaught errors are handled.

The Zone class is not subclassable, but users can provide custom zones by forking an existing zone (usually Zone.current) with a ZoneSpecification. This is similar to creating a new class that extends the base Zone class and that overrides some methods, except without actually creating a new class. Instead the overriding methods are provided as functions that explicitly take the equivalent of their own class, the "super" class and the this object as parameters.

Asynchronous callbacks always run in the context of the zone where they were scheduled. This is implemented using two steps:

  1. The callback is first registered using one of registerCallback, registerUnaryCallback, or registerBinaryCallback. This allows the zone to record that a callback exists and potentially modify it (by returning a different callback). The code doing the registration (e.g. Future.then) also remembers the current zone so that it can later run the callback in that zone.
  2. At a later point the registered callback is run in the remembered zone, using one of run, runUnary or runBinary.

This is all handled internally by the platform code and most users don't need to worry about it. However, developers of new asynchronous operations, provided by the underlying system, must follow the protocol to be zone compatible.

For convenience, zones provide bindCallback (and the corresponding bindUnaryCallback and bindBinaryCallback) to make it easier to respect the zone contract: these functions first invoke the corresponding register functions and then wrap the returned function so that it runs in the current zone when it is later asynchronously invoked.

Similarly, zones provide bindCallbackGuarded (and the corresponding bindUnaryCallbackGuarded and bindBinaryCallbackGuarded), when the callback should be invoked through Zone.runGuarded.

Static

rootconstant
static const Zone root = _rootZone

The root zone.

All isolate entry functions (main or spawned functions) start running in the root zone (that is, Zone.current is identical to Zone.root when the entry function is called). If no custom zone is created, the rest of the program always runs in the root zone.

The root zone implements the default behavior of all zone operations. Many methods, like registerCallback do the bare minimum required of the function, and are only provided as a hook for custom zones. Others, like scheduleMicrotask, interact with the underlying system to implement the desired behavior.

currentstaticgetter
static Zone get current

The zone that is currently active.

Properties

parentgetter
Zone? get parent

The parent zone of the this zone.

Is null if this is the root zone.

Zones are created by fork on an existing zone, or by runZoned which forks the current zone. The new zone's parent zone is the zone it was forked from.

errorZonegetter
Zone get errorZone

The error zone is responsible for dealing with uncaught errors.

This is the closest parent zone of this zone that provides a handleUncaughtError method.

Asynchronous errors in futures never cross zone boundaries between zones with different error handlers.

Example:

import 'raya:async';

main() {
  var future;
  runZonedGuarded(() {
    // The asynchronous error is caught by the custom zone which prints
    // 'asynchronous error'.
    future = Future.error("asynchronous error");
  }, (error) { print(error); });  // Creates a zone with an error handler.
  // The following `catchError` handler is never invoked, because the
  // custom zone created by the call to `runZonedGuarded` provides an
  // error handler.
  future.catchError((error) { throw "is never reached"; });
}

Note that errors cannot enter a child zone with a different error handler either:

import 'raya:async';

main() {
  runZonedGuarded(() {
    // The following asynchronous error is *not* caught by the `catchError`
    // in the nested zone, since errors are not to cross zone boundaries
    // with different error handlers.
    // Instead the error is handled by the current error handler,
    // printing "Caught by outer zone: asynchronous error".
    var future = Future.error("asynchronous error");
    runZonedGuarded(() {
      future.catchError((e) { throw "is never reached"; });
    }, (error, stack) { throw "is never reached"; });
  }, (error, stack) { print("Caught by outer zone: $error"); });
}

Methods

void handleUncaughtError(Object error, StackTrace stackTrace)

Handles uncaught asynchronous errors.

There are two kind of asynchronous errors that are handled by this function:

  1. Uncaught errors that were thrown in asynchronous callbacks, for example, a throw in the function passed to Timer.run.
  2. Asynchronous errors that are pushed through Future and Stream chains, but for which nobody registered an error handler. Most asynchronous classes, like Future or Stream push errors to their listeners. Errors are propagated this way until either a listener handles the error (for example with Future.catchError), or no listener is available anymore. In the latter case, futures and streams invoke the zone's handleUncaughtError.

By default, when handled by the root zone, uncaught asynchronous errors are treated like uncaught synchronous exceptions.

Example
import 'raya:async';

void main() {
  final caught = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (self, parent, zone, error, stack) => caught.add('$error'),
  ));
  zone.handleUncaughtError(StateError('disk full'), StackTrace.empty);
  zone.handleUncaughtError(ArgumentError('bad id'), StackTrace.empty);
  print('handled by the zone: $caught');
}
Output
handled by the zone: [Bad state: disk full, Invalid argument(s): bad id]
bool inSameErrorZone(Zone otherZone)

Whether this zone and otherZone are in the same error zone.

Two zones are in the same error zone if they have the same errorZone.

Example
import 'raya:async';

void main() {
  final root = Zone.current;
  final plain = root.fork();
  final guarded = root.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) {},
  ));
  print('plain fork shares errors with root: ${plain.inSameErrorZone(root)}');
  print('a zone with its own handler:        ${guarded.inSameErrorZone(root)}');
}
Output
plain fork shares errors with root: true
a zone with its own handler:        false
forkmethod
Zone fork({ZoneSpecification? specification, Map<Object?, Object?>? zoneValues})

Creates a new zone as a child zone of this zone.

The new zone uses the closures in the given specification to override the parent zone's behavior. All specification entries that are null inherit the behavior from the parent zone (this).

The new zone inherits the stored values (accessed through [operator []]) of this zone and updates them with values from zoneValues, which either adds new values or overrides existing ones.

Note that the fork operation is interceptable. A zone can thus change the zone specification (or zone values), giving the parent zone full control over the child zone.

Example
import 'raya:async';

void main() {
  final child = Zone.current.fork(zoneValues: {#user: 'ada'});
  print('child sees user: ${child[#user]}');
  print('parent sees user: ${Zone.current[#user]}');
  final grandchild = child.fork(zoneValues: {#role: 'admin'});
  print('grandchild inherits: ${grandchild[#user]}, ${grandchild[#role]}');
}
Output
child sees user: ada
parent sees user: null
grandchild inherits: ada, admin
runmethod
R run<R>(R action())

Executes action in this zone.

By default (as implemented in the root zone), runs action with current set to this zone.

If action throws, the synchronous exception is not caught by the zone's error handler. Use runGuarded to achieve that.

Since the root zone is the only zone that can modify the value of current, custom zones intercepting run should always delegate to their parent zone. They may take actions before and after the call.

Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#requestId: 42});
  final result = zone.run(() => 'handled request ${Zone.current[#requestId]}');
  print(result);
  print('back outside: ${Zone.current[#requestId]}');
}
Output
handled request 42
back outside: null
runUnarymethod
R runUnary<R, T>(R action(T argument), T argument)

Executes the given action with argument in this zone.

As run except that action is called with one argument instead of none.

Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#unit: 'cm'});
  String label(int n) => '$n ${Zone.current[#unit]}';
  print(zone.runUnary(label, 15));
}
Output
15 cm
runBinarymethod
R runBinary<R, T1, T2>(R action(T1 argument1, T2 argument2), T1 argument1, T2 argument2)

Executes the given action with argument1 and argument2 in this zone.

As run except that action is called with two arguments instead of none.

Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#sep: ' x '});
  String size(int w, int h) => '$w${Zone.current[#sep]}$h';
  print(zone.runBinary(size, 1920, 1080));
}
Output
1920 x 1080
void runGuarded(void action())

Executes the given action in this zone and catches synchronous errors.

This function is equivalent to:

try {
  this.run(action);
} catch (e, s) {
  this.handleUncaughtError(e, s);
}

See run.

Example
import 'raya:async';

void main() {
  final errors = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add('$e'),
  ));
  zone.runGuarded(() => throw FormatException('bad header'));
  print('runGuarded did not rethrow; zone got: $errors');
}
Output
runGuarded did not rethrow; zone got: [FormatException: bad header]
void runUnaryGuarded<T>(void action(T argument), T argument)

Executes the given action with argument in this zone and catches synchronous errors.

See runGuarded.

Example
import 'raya:async';

void main() {
  final errors = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add('$e'),
  ));
  void parse(String s) => print('parsed ${int.parse(s)}');
  zone.runUnaryGuarded(parse, '12');
  zone.runUnaryGuarded(parse, 'twelve');
  print('errors: ${errors.length}');
}
Output
parsed 12
errors: 1
void runBinaryGuarded<T1, T2>(void action(T1 argument1, T2 argument2), T1 argument1, T2 argument2)

Executes the given action with argument1 and argument2 in this zone and catches synchronous errors.

See runGuarded.

Example
import 'raya:async';

void main() {
  final errors = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add(e.runtimeType.toString()),
  ));
  void divide(int a, int b) => print('$a ~/ $b = ${a ~/ b}');
  zone.runBinaryGuarded(divide, 7, 2);
  zone.runBinaryGuarded(divide, 7, 0);
  print('errors caught: ${errors.length}');
}
Output
7 ~/ 2 = 3
errors caught: 1
ZoneCallback<R> registerCallback<R>(R callback())

Registers the given callback in this zone.

When implementing an asynchronous primitive that uses callbacks, the callback must be registered using registerCallback at the point where the user provides the callback. This allows zones to record other information that they need at the same time, perhaps even wrapping the callback, so that the callback is prepared when it is later run in the same zones (using run). For example, a zone may decide to store the stack trace (at the time of the registration) with the callback.

Returns the callback that should be used in place of the provided callback. Frequently zones simply return the original callback.

Custom zones may intercept this operation. The default implementation in Zone.root returns the original callback unchanged.

Example
import 'raya:async';

void main() {
  var registered = 0;
  final zone = Zone.current.fork(specification: ZoneSpecification(
    registerCallback: <R>(self, parent, zone, f) {
      registered++;
      return parent.registerCallback(zone, f);
    },
  ));
  final cb = zone.registerCallback(() => 'ran');
  print('registered: $registered, callback returns: ${cb()}');
}
Output
registered: 1, callback returns: ran
ZoneUnaryCallback<R, T> registerUnaryCallback<R, T>(R callback(T arg))

Registers the given callback in this zone.

Similar to registerCallback but with a unary callback.

Example
import 'raya:async';

void main() {
  final seen = <Object?>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    // Wrap every unary callback so its arguments are logged.
    registerUnaryCallback: <R, T>(self, parent, zone, f) =>
        parent.registerUnaryCallback<R, T>(zone, (T x) {
          seen.add(x);
          return f(x);
        }),
  ));
  final square = zone.registerUnaryCallback<int, int>((x) => x * x);
  print('square(9) = ${square(9)}, square(4) = ${square(4)}');
  print('arguments logged: $seen');
}
Output
square(9) = 81, square(4) = 16
arguments logged: [9, 4]
ZoneBinaryCallback<R, T1, T2> registerBinaryCallback<R, T1, T2>(R callback(T1 arg1, T2 arg2))

Registers the given callback in this zone.

Similar to registerCallback but with a binary callback.

Example
import 'raya:async';

void main() {
  final names = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    registerBinaryCallback: <R, T1, T2>(self, parent, zone, f) {
      names.add('binary');
      return parent.registerBinaryCallback(zone, f);
    },
  ));
  final add = zone.registerBinaryCallback<int, int, int>((a, b) => a + b);
  print('add(2, 3) = ${add(2, 3)}, hooks seen: $names');
}
Output
add(2, 3) = 5, hooks seen: [binary]
ZoneCallback<R> bindCallback<R>(R callback())

Registers the provided callback and returns a function that will execute in this zone.

Equivalent to:

ZoneCallback registered = this.registerCallback(callback);
return () => this.run(registered);
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#lang: 'fr'});
  final hello = zone.bindCallback(() => Zone.current[#lang] == 'fr' ? 'bonjour' : 'hello');
  // Called from outside, it still runs inside the zone.
  print('outside zone value: ${Zone.current[#lang]}');
  print('bound callback says: ${hello()}');
}
Output
outside zone value: null
bound callback says: bonjour
ZoneUnaryCallback<R, T> bindUnaryCallback<R, T>(R callback(T argument))

Registers the provided callback and returns a function that will execute in this zone.

Equivalent to:

ZoneCallback registered = this.registerUnaryCallback(callback);
return (arg) => this.runUnary(registered, arg);
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#currency: 'EUR'});
  final price = zone.bindUnaryCallback((int cents) => '${cents / 100} ${Zone.current[#currency]}');
  print(price(1250));
}
Output
12.5 EUR
ZoneBinaryCallback<R, T1, T2> bindBinaryCallback<R, T1, T2>(R callback(T1 argument1, T2 argument2))

Registers the provided callback and returns a function that will execute in this zone.

Equivalent to:

ZoneCallback registered = registerBinaryCallback(callback);
return (arg1, arg2) => this.runBinary(registered, arg1, arg2);
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(zoneValues: {#precision: 2});
  final ratio = zone.bindBinaryCallback((num a, num b) => (a / b).toStringAsFixed(Zone.current[#precision] as int));
  print('22 / 7 = ${ratio(22, 7)}');
}
Output
22 / 7 = 3.14
void Function() bindCallbackGuarded(void Function() callback)

Registers the provided callback and returns a function that will execute in this zone.

When the function executes, errors are caught and treated as uncaught errors.

Equivalent to:

ZoneCallback registered = this.registerCallback(callback);
return () => this.runGuarded(registered);
Example
import 'raya:async';

void main() {
  final errors = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add('$e'),
  ));
  final task = zone.bindCallbackGuarded(() => throw StateError('task failed'));
  task();
  print('caller continues; zone recorded: $errors');
}
Output
caller continues; zone recorded: [Bad state: task failed]
void Function(T) bindUnaryCallbackGuarded<T>(void callback(T argument))

Registers the provided callback and returns a function that will execute in this zone.

When the function executes, errors are caught and treated as uncaught errors.

Equivalent to:

ZoneCallback registered = this.registerUnaryCallback(callback);
return (arg) => this.runUnaryGuarded(registered, arg);
Example
import 'raya:async';

void main() {
  final errors = <Object>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add(e),
  ));
  final onItem = zone.bindUnaryCallbackGuarded((String s) => print('item ${int.parse(s)}'));
  ['1', 'x', '3'].forEach(onItem);
  print('bad items: ${errors.length}');
}
Output
item 1
item 3
bad items: 1
void Function(T1, T2) bindBinaryCallbackGuarded<T1, T2>(void callback(T1 argument1, T2 argument2))

Registers the provided callback and returns a function that will execute in this zone.

Equivalent to:

ZoneCallback registered = registerBinaryCallback(callback);
return (arg1, arg2) => this.runBinaryGuarded(registered, arg1, arg2);
Example
import 'raya:async';

void main() {
  final errors = <Object>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => errors.add(e),
  ));
  final put = zone.bindBinaryCallbackGuarded((String k, int v) {
    if (v < 0) throw RangeError.value(v, k);
    print('$k = $v');
  });
  put('a', 1);
  put('b', -1);
  print('rejected: ${errors.length}');
}
Output
a = 1
rejected: 1
AsyncError? errorCallback(Object error, StackTrace? stackTrace)

Intercepts errors when added programmatically to a Future or Stream.

When calling Completer.completeError, StreamController.addError, or some Future constructors, the current zone is allowed to intercept and replace the error.

Future constructors invoke this function when the error is received directly, for example with Future.error, or when the error is caught synchronously, for example with Future.sync.

There is no guarantee that an error is only sent through errorCallback once. Libraries that use intermediate controllers or completers might end up invoking errorCallback multiple times.

Returns null if no replacement is desired. Otherwise returns an instance of AsyncError holding the new pair of error and stack trace.

Custom zones may intercept this operation.

Implementations of a new asynchronous primitive that converts synchronous errors to asynchronous errors rarely need to invoke errorCallback, since errors are usually reported through future completers or stream controllers.

Example
import 'raya:async';

void main() {
  print('root zone: ${Zone.current.errorCallback(StateError('x'), null)}');
  final zone = Zone.current.fork(specification: ZoneSpecification(
    errorCallback: (self, parent, zone, error, stack) =>
        AsyncError('wrapped: $error', stack ?? StackTrace.empty),
  ));
  final replaced = zone.errorCallback('boom', null);
  print('custom zone: ${replaced?.error}');
}
Output
root zone: null
custom zone: wrapped: boom
void scheduleMicrotask(void Function() callback)

Runs callback asynchronously in this zone.

The global scheduleMicrotask delegates to the current zone's scheduleMicrotask. The root zone's implementation interacts with the underlying system to schedule the given callback as a microtask.

Custom zones may intercept this operation (for example to wrap the given callback), or to implement their own microtask scheduler. In the latter case, they will usually still use the parent zone's ZoneDelegate.scheduleMicrotask to attach themselves to the existing event loop.

Example
import 'raya:async';

Future<void> main() async {
  final order = <String>[];
  final zone = Zone.current.fork(zoneValues: {#tag: 'z'});
  zone.scheduleMicrotask(() => order.add('microtask in ${Zone.current[#tag]}'));
  order.add('sync');
  await Future(() {});
  print(order);
}
Output
[sync, microtask in z]
Timer createTimer(Duration duration, void Function() callback)

Creates a Timer where the callback is executed in this zone.

Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<String>();
  final zone = Zone.current.fork(zoneValues: {#job: 'cleanup'});
  zone.createTimer(Duration.zero, () => done.complete('timer ran ${Zone.current[#job]}'));
  print('timer scheduled');
  print(await done.future);
}
Output
timer scheduled
timer ran cleanup
Timer createPeriodicTimer(Duration period, void callback(Timer timer))

Creates a periodic Timer where the callback is executed in this zone.

Example
import 'raya:async';

Future<void> main() async {
  final done = Completer<void>();
  var ticks = 0;
  Zone.current.createPeriodicTimer(const Duration(milliseconds: 1), (t) {
    ticks++;
    if (ticks == 3) {
      t.cancel();
      done.complete();
    }
  });
  await done.future;
  print('ticked $ticks times, then cancelled');
}
Output
ticked 3 times, then cancelled
printmethod
void print(String line)

Prints the given line.

The global print function delegates to the current zone's print function which makes it possible to intercept printing.

Example:

import 'raya:async';

main() {
  runZoned(() {
    // Ends up printing: "Intercepted: in zone".
    print("in zone");
  }, zoneSpecification: new ZoneSpecification(
      print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
    parent.print(zone, "Intercepted: $line");
  }));
}
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(specification: ZoneSpecification(
    print: (self, parent, zone, line) => parent.print(zone, '[log] $line'),
  ));
  zone.print('direct');
  zone.run(() => print('from print()'));
  print('outside: no prefix');
}
Output
[log] direct
[log] from print()
outside: no prefix

Operators

operator []operator
dynamic operator [](Object? key)

Retrieves the zone-value associated with key.

If this zone does not contain the value looks up the same key in the parent zone. If the key is not found returns null.

Any object can be used as key, as long as it has compatible operator == and hashCode implementations. By controlling access to the key, a zone can grant or deny access to the zone value.

Example
import 'raya:async';

void main() {
  const key = #traceId;
  print('root: ${Zone.current[key]}');
  runZoned(() {
    print('inside: ${Zone.current[key]}');
    runZoned(() => print('nested override: ${Zone.current[key]}'), zoneValues: {key: 'abc-2'});
  }, zoneValues: {key: 'abc-1'});
}
Output
root: null
inside: abc-1
nested override: abc-2
abstract final class ZoneDelegate

An adapted view of the parent zone.

This class allows the implementation of a zone method to invoke methods on the parent zone while retaining knowledge of the originating zone.

Custom zones (created through Zone.fork or runZoned) can provide implementations of most methods of zones. This is similar to overriding methods on Zone, except that this mechanism doesn't require subclassing.

A custom zone function (provided through a ZoneSpecification) typically records or wraps its parameters and then delegates the operation to its parent zone using the provided ZoneDelegate.

While zones have access to their parent zone (through Zone.parent) it is recommended to call the methods on the provided parent delegate for two reasons:

  1. The delegate methods take an additional zone argument which is the zone the action has been initiated in.
  2. Delegate calls are more efficient, since the implementation knows how to skip zones that would just delegate to their parents.

Methods

void handleUncaughtError(Zone zone, Object error, StackTrace stackTrace)
Example
import 'raya:async';

void main() {
  final log = <String>[];
  final outer = Zone.current.fork(specification: ZoneSpecification(
    handleUncaughtError: (s, p, z, e, st) => log.add('outer handled $e'),
  ));
  final inner = outer.fork(specification: ZoneSpecification(
    handleUncaughtError: (self, parent, zone, e, st) {
      log.add('inner saw $e, passing up');
      parent.handleUncaughtError(zone, e, st);
    },
  ));
  inner.runGuarded(() => throw 'oops');
  log.forEach(print);
}
Output
inner saw oops, passing up
outer handled oops
runmethod
R run<R>(Zone zone, R f())
Example
import 'raya:async';

void main() {
  var runs = 0;
  final zone = Zone.current.fork(specification: ZoneSpecification(
    run: <R>(self, parent, zone, f) {
      runs++;
      return parent.run(zone, f);
    },
  ));
  zone.run(() => 1);
  zone.run(() => 2);
  print('run handler called $runs times');
}
Output
run handler called 2 times
runUnarymethod
R runUnary<R, T>(Zone zone, R f(T arg), T arg)
Example
import 'raya:async';

void main() {
  final args = <Object?>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    runUnary: <R, T>(self, parent, zone, f, arg) {
      args.add(arg);
      return parent.runUnary(zone, f, arg);
    },
  ));
  final r = zone.runUnary((int x) => x + 1, 41);
  print('result $r, arguments seen: $args');
}
Output
result 42, arguments seen: [41]
runBinarymethod
R runBinary<R, T1, T2>(Zone zone, R f(T1 arg1, T2 arg2), T1 arg1, T2 arg2)
Example
import 'raya:async';

void main() {
  final calls = <String>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    runBinary: <R, T1, T2>(self, parent, zone, f, a, b) {
      calls.add('($a, $b)');
      return parent.runBinary(zone, f, a, b);
    },
  ));
  final r = zone.runBinary((int a, int b) => a * b, 6, 7);
  print('result $r, calls $calls');
}
Output
result 42, calls [(6, 7)]
ZoneCallback<R> registerCallback<R>(Zone zone, R f())
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(specification: ZoneSpecification(
    registerCallback: <R>(self, parent, zone, f) =>
        parent.registerCallback(zone, () => f()),
  ));
  final cb = zone.registerCallback(() => 'wrapped by the parent delegate');
  print(cb());
}
Output
wrapped by the parent delegate
ZoneUnaryCallback<R, T> registerUnaryCallback<R, T>(Zone zone, R f(T arg))
Example
import 'raya:async';

void main() {
  var wrapped = 0;
  final zone = Zone.current.fork(specification: ZoneSpecification(
    registerUnaryCallback: <R, T>(self, parent, zone, f) {
      wrapped++;
      return parent.registerUnaryCallback(zone, f);
    },
  ));
  final cb = zone.registerUnaryCallback((String s) => s.length);
  print('length: ${cb('raya')}, wrapped $wrapped callback(s)');
}
Output
length: 4, wrapped 1 callback(s)
ZoneBinaryCallback<R, T1, T2> registerBinaryCallback<R, T1, T2>(Zone zone, R f(T1 arg1, T2 arg2))
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(specification: ZoneSpecification(
    registerBinaryCallback: <R, T1, T2>(self, parent, zone, f) =>
        parent.registerBinaryCallback(zone, f),
  ));
  final join = zone.registerBinaryCallback((String a, String b) => '$a-$b');
  print(join('left', 'right'));
}
Output
left-right
AsyncError? errorCallback(Zone zone, Object error, StackTrace? stackTrace)
Example
import 'raya:async';

void main() {
  final zone = Zone.current.fork(specification: ZoneSpecification(
    errorCallback: (self, parent, zone, error, stack) {
      if (error is String) return AsyncError(FormatException(error), stack ?? StackTrace.empty);
      return parent.errorCallback(zone, error, stack);
    },
  ));
  print('string error: ${zone.errorCallback('bad input', null)?.error.runtimeType}');
  print('other error: ${zone.errorCallback(StateError('x'), null)}');
}
Output
string error: FormatException
other error: null
void scheduleMicrotask(Zone zone, void f())
Example
import 'raya:async';

Future<void> main() async {
  var count = 0;
  final zone = Zone.current.fork(specification: ZoneSpecification(
    scheduleMicrotask: (self, parent, zone, f) {
      count++;
      parent.scheduleMicrotask(zone, f);
    },
  ));
  zone.run(() {
    scheduleMicrotask(() {});
    Future.microtask(() {});
  });
  await Future(() {});
  print('microtasks scheduled through the zone: $count');
}
Output
microtasks scheduled through the zone: 2
Timer createTimer(Zone zone, Duration duration, void f())
Example
import 'raya:async';

Future<void> main() async {
  final durations = <Duration>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    createTimer: (self, parent, zone, d, f) {
      durations.add(d);
      return parent.createTimer(zone, Duration.zero, f); // fast-forward
    },
  ));
  final done = Completer<void>();
  zone.run(() => Timer(const Duration(hours: 1), done.complete));
  await done.future;
  print('asked for $durations, ran immediately');
}
Output
asked for [1:00:00.000000], ran immediately
Timer createPeriodicTimer(Zone zone, Duration period, void f(Timer timer))
Example
import 'raya:async';

Future<void> main() async {
  final periods = <Duration>[];
  final zone = Zone.current.fork(specification: ZoneSpecification(
    createPeriodicTimer: (self, parent, zone, p, f) {
      periods.add(p);
      return parent.createPeriodicTimer(zone, const Duration(milliseconds: 1), f);
    },
  ));
  final done = Completer<void>();
  var n = 0;
  zone.run(() => Timer.periodic(const Duration(minutes: 1), (t) {
        if (++n == 2) {
          t.cancel();
          done.complete();
        }
      }));
  await done.future;
  print('requested ${periods.single}, ticked $n times quickly');
}
Output
requested 0:01:00.000000, ticked 2 times quickly
printmethod
void print(Zone zone, String line)
Example
import 'raya:async';

void main() {
  var line = 0;
  runZoned(() {
    print('first');
    print('second');
  }, zoneSpecification: ZoneSpecification(
    print: (self, parent, zone, s) => parent.print(zone, '${++line}: $s'),
  ));
}
Output
1: first
2: second
forkmethod
Zone fork(Zone zone, ZoneSpecification? specification, Map? zoneValues)
Example
import 'raya:async';

void main() {
  var forks = 0;
  final zone = Zone.current.fork(specification: ZoneSpecification(
    fork: (self, parent, zone, spec, values) {
      forks++;
      return parent.fork(zone, spec, {...?values, #forkedBy: 'parent'});
    },
  ));
  final child = zone.fork(zoneValues: {#n: 1});
  print('forks: $forks, child values: ${child[#n]}, ${child[#forkedBy]}');
}
Output
forks: 1, child values: 1, parent
final class ZoneSpecification

A parameter object with custom zone function handlers for Zone.fork.

A zone specification is a parameter object passed to Zone.fork and any underlying ForkHandler custom implementations. The individual handlers, if set to a non-null value, will be the implementation of the corresponding Zone methods for a forked zone created using this zone specification.

Handlers have the same signature as the same-named methods on Zone, but receive three additional arguments:

  1. The zone the handlers are attached to (the "self" zone). This is the zone created by Zone.fork where the handler is passed as part of the zone delegation.
  2. A ZoneDelegate to the parent zone.
  3. The "current" zone at the time the request was made. The self zone is always a parent zone of the current zone.

Handlers can either stop propagating the request (by simply not calling the parent handler), or forward to the parent zone, potentially modifying the arguments on the way.

Constructors

const ZoneSpecification({this.handleUncaughtError, this.run, this.runUnary, this.runBinary, this.registerCallback, this.registerUnaryCallback, this.registerBinaryCallback, this.errorCallback, this.scheduleMicrotask, this.createTimer, this.createPeriodicTimer, this.print, this.fork})

Creates a specification with the provided handlers.

If the handleUncaughtError is provided, the new zone will be a new "error zone" which will prevent errors from flowing into other error zones (see Zone.errorZone, Zone.inSameErrorZone).

Example
import 'raya:async';

void main() {
  final log = <String>[];
  runZoned(() {
    print('hello');
    scheduleMicrotask(() => print('later'));
  }, zoneSpecification: ZoneSpecification(
    print: (self, parent, zone, line) => log.add(line),
  ));
  Future(() => print('captured: $log'));
}
Output
captured: [hello, later]
ZoneSpecification.from(ZoneSpecification other, {HandleUncaughtErrorHandler? handleUncaughtError, RunHandler? run, RunUnaryHandler? runUnary, RunBinaryHandler? runBinary, RegisterCallbackHandler? registerCallback, RegisterUnaryCallbackHandler? registerUnaryCallback, RegisterBinaryCallbackHandler? registerBinaryCallback, ErrorCallbackHandler? errorCallback, ScheduleMicrotaskHandler? scheduleMicrotask, CreateTimerHandler? createTimer, CreatePeriodicTimerHandler? createPeriodicTimer, PrintHandler? print, ForkHandler? fork})

Creates a specification from other and provided handlers.

The created zone specification has the handlers of other and any individually provided handlers. If a handler is provided both through other and individually, the individually provided handler overrides the one from other.

Example
import 'raya:async';

void main() {
  final base = ZoneSpecification(print: (s, p, z, line) => p.print(z, '[base] $line'));
  // Copy base, replacing only the print hook.
  final loud = ZoneSpecification.from(base, print: (s, p, z, line) => p.print(z, line.toUpperCase()));
  Zone.current.fork(specification: base).print('quiet');
  Zone.current.fork(specification: loud).print('loud');
  print('has print hook: ${loud.print != null}, has run hook: ${loud.run != null}');
}
Output
[base] quiet
LOUD
has print hook: true, has run hook: false

Properties

final HandleUncaughtErrorHandler? handleUncaughtError

A custom Zone.handleUncaughtError implementation for a new zone.

runfield
final RunHandler? run

A custom Zone.run implementation for a new zone.

final RunUnaryHandler? runUnary

A custom Zone.runUnary implementation for a new zone.

final RunBinaryHandler? runBinary

A custom Zone.runBinary implementation for a new zone.

final RegisterCallbackHandler? registerCallback

A custom Zone.registerCallback implementation for a new zone.

final RegisterUnaryCallbackHandler? registerUnaryCallback

A custom Zone.registerUnaryCallback implementation for a new zone.

final RegisterBinaryCallbackHandler? registerBinaryCallback

A custom Zone.registerBinaryCallback implementation for a new zone.

final ErrorCallbackHandler? errorCallback

A custom Zone.errorCallback implementation for a new zone.

final ScheduleMicrotaskHandler? scheduleMicrotask

A custom Zone.scheduleMicrotask implementation for a new zone.

final CreateTimerHandler? createTimer

A custom Zone.createTimer implementation for a new zone.

final CreatePeriodicTimerHandler? createPeriodicTimer

A custom Zone.createPeriodicTimer implementation for a new zone.

printfield
final PrintHandler? print

A custom Zone.print implementation for a new zone.

forkfield
final ForkHandler? fork

A custom Zone.handleUncaughtError implementation for a new zone.