getFirstResultInStream<T> function
Implementation
Future<T?> getFirstResultInStream<T>(
Stream<T> stream,
Duration timeout,
) async {
// Creates a Completer to store the first result
final firstResultCompleter = Completer<T?>();
// Subscribes to the stream
final subscription = stream.listen((event) {
// If this is the first result, completes the Completer
if (firstResultCompleter.isCompleted) return;
firstResultCompleter.complete(event);
});
// Starts a timer to cancel the subscription after the timeout
Timer(timeout, subscription.cancel);
// Returns the Completer's Future. This Future will complete when the first result is received or when the timeout expires.
return firstResultCompleter.future.timeout(timeout);
}