onSnapshot method Null safety

Stream<RecordSnapshot<K, V>?> onSnapshot(
  1. Database database
)

Get a stream of a record snapshot from the database.

It allows listening to a single instance of a record.

Implementation

Stream<RecordSnapshot<K, V>?> onSnapshot(Database database) {
  var db = getDatabase(database);
  late RecordListenerController<K, V> ctlr;
  ctlr = db.listener.addRecord(this, onListen: () {
    // Read right away
    () async {
      await db.notificationLock.synchronized(() async {
        // Don't crash here, the database might have been closed
        try {
          // Add the existing snapshot
          var snapshot = await getSnapshot(database);
          if (debugListener) {
            print('matching $ctlr: $snapshot on $this');
          }
          ctlr.add(snapshot);
        } catch (error, stackTrace) {
          ctlr.addError(error, stackTrace);
        }
      });
    }();
  });
  return ctlr.stream;
}