firstToFuture<T> method

Future<T> firstToFuture<T>(
  1. Stream<T> stream
)

Waits for the first value from the Stream and returns it as a Future.

Implementation

Future<T> firstToFuture<T>(Stream<T> stream) {
  final completer = Completer<T>();
  StreamSubscription<T>? subscription;

  subscription = stream.listen(
    (data) {
      if (!completer.isCompleted) {
        completer.complete(data);
        subscription?.cancel();
      }
    },
    onError: (Object e) {
      if (!completer.isCompleted) {
        completer.completeError(e);
        subscription?.cancel();
      }
    },
    onDone: () {
      if (!completer.isCompleted) {
        completer.completeError(
          StateError(
            '[firstToFuture] Stream completed without emitting any values',
          ),
        );
      }
    },
    cancelOnError: true,
  );

  return completer.future;
}