defaultWatchStorageSize<T extends DatumEntityBase> static method

  1. @visibleForTesting
Stream<int> defaultWatchStorageSize<T extends DatumEntityBase>(
  1. LocalAdapter<T> adapter, {
  2. String? userId,
})

Reactively watches the storage size in bytes for a given user.

Emits the current size immediately and then a new size whenever the underlying data changes. Adapters can override this for a more efficient implementation if their storage engine supports it. The default implementation is also available as a static method for testing purposes.

Implementation

@visibleForTesting
static Stream<int> defaultWatchStorageSize<T extends DatumEntityBase>(LocalAdapter<T> adapter, {String? userId}) {
  final changes = adapter
      .changeStream()
      // Filter changes to only include the relevant user.
      ?.where((event) => userId == null || event.userId == userId)
      // When a change occurs, recalculate the size.
      .asyncMap((_) => adapter.getStorageSize(userId: userId));

  if (changes == null) return Stream.value(0);

  // Use a transformer to emit the initial value first, then subsequent changes.
  return changes.transform(
    StreamTransformer.fromBind((stream) async* {
      yield await adapter.getStorageSize(userId: userId);
      yield* stream;
    }),
  );
}