once method
Completes with the first event of type and stops listening.
This is a listener, not a read. It answers from data the client already holds (pending local
writes included), else it waits for the server with no timeout, also while offline; get
fails with unavailable after 3 seconds instead. With a child type it completes with the
first child event, so it waits until a child exists or changes. It fails with the error of the
stream (permission-denied when the rules refuse the listen), and with database-closed
when FirebaseDatabase.close ends the stream first.
final DatabaseEvent e = await db.ref('config').once();
print(e.snapshot.value);
Implementation
Future<DatabaseEvent> once([
DatabaseEventType type = DatabaseEventType.value,
]) {
final Completer<DatabaseEvent> completer = Completer<DatabaseEvent>();
late final StreamSubscription<DatabaseEvent> subscription;
subscription = _stream(<EventType>{_coreType(type)}).listen(
(DatabaseEvent event) {
if (completer.isCompleted) {
return;
}
unawaited(subscription.cancel());
completer.complete(event);
},
onError: (Object error, StackTrace stackTrace) {
if (!completer.isCompleted) {
completer.completeError(error, stackTrace);
}
},
onDone: () {
if (!completer.isCompleted) {
// The stream ends with done only at close; the Future still fails.
completer.completeError(
database.isClosed
? database.closedError()
: StateError('The stream ended before an event of type $type.'),
);
}
},
cancelOnError: true,
);
return completer.future;
}