Stream<T>.error constructor

  1. @Since("2.5")
Stream<T>.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. The error must not be null.

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.

Implementation

@Since("2.5")
factory Stream.error(Object error, [StackTrace stackTrace]) {
  ArgumentError.checkNotNull(error, "error");
  return (_AsyncStreamController<T>(null, null, null, null)
        .._addError(error, stackTrace ?? AsyncError.defaultStackTrace(error))
        .._closeUnchecked())
      .stream;
}