first<T> static method

Future<T?> first<T>(
  1. Stream<T> stream
)

Returns the first element, or null if not element at all. Unlike Stream.first, it won't throw StateError.

Implementation

static Future<T?> first<T>(Stream<T> stream) {
  final c = Completer<T?>(),
    subscription = stream.listen(null,
        onError: c.completeError,
        onDone: c.complete, cancelOnError: true);
  subscription.onData((data) {
    c.complete(data);
    InvokeUtil.invokeSafely(subscription.cancel);
  });
  return c.future;
}