onSnapshot method

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 ctlr.lock.synchronized(() async {
          // Don't crash here, the database might have been closed
          try {
            // Add the existing snapshot
            var snapshot = await getSnapshot(database);
            if (debugListener) {
              // ignore: avoid_print
              print('matching $ctlr: $snapshot on $this');
            }
            ctlr.add(snapshot);
          } catch (error, stackTrace) {
            ctlr.addError(error, stackTrace);
          }
        });
      }();
    },
  );
  return ctlr.stream;
}