performDocumentRead method

  1. @override
Stream<Snapshot> performDocumentRead(
  1. DocumentReadRequest request
)
override

Implementation

@override
Stream<Snapshot> performDocumentRead(
  DocumentReadRequest request,
) async* {
  // Start master read
  final masterFuture = super.performDocumentRead(request).last;

  // Read from cache and yield it
  Snapshot cacheSnapshot;
  try {
    cacheSnapshot = await request.delegateTo(cache).last;
  } on DatabaseException {
    // Ignore
  }
  if (cacheSnapshot != null && cacheSnapshot.exists) {
    yield (cacheSnapshot);
  }

  // Finish master read and yield it
  final masterSnapshot = await masterFuture;
  yield (masterSnapshot);

  try {
    if (masterSnapshot.exists) {
      if (!const DeepCollectionEquality()
          .equals(cacheSnapshot?.data, masterSnapshot.data)) {
        // Master and cache snapshots are different.
        // Update cached version.
        await DocumentUpsertRequest(
          document: request.document,
          data: masterSnapshot.data,
          reach: request.reach,
        ).delegateTo(cache);
      }
    } else if (cacheSnapshot?.exists ?? false) {
      // Remove cached version.
      await DocumentDeleteRequest(
        document: request.document,
        mustExist: false,
        reach: request.reach,
      ).delegateTo(cache);
    }
  } on DatabaseException {
    // Ignore
  }
}