watchById method

Stream<T?> watchById(
  1. String id,
  2. String? userId, {
  3. bool includeDeleted = false,
})

Watches a single entity by its ID, emitting the item on change or null if deleted. A soft-delete tombstone emits null like a hard delete would, unless includeDeleted is true. Returns null if the adapter does not support reactive queries.

Implementation

Stream<T?> watchById(String id, String? userId, {bool includeDeleted = false}) {
  _ensureInitialized();
  final adapterStream = localAdapter.watchById(id, userId: userId);
  if (adapterStream == null) return Stream<T?>.empty();

  return adapterStream.asyncMap((emitted) async {
    final item = !includeDeleted && (emitted?.isDeleted ?? false) ? null : emitted;
    if (item == null) {
      return null;
    }
    try {
      return await _applyPostFetchTransforms(item);
    } catch (e, stack) {
      _logger.error('Failed to apply post-fetch transforms to entity $id: $e', stack);
      return item; // Return original entity if transform fails
    }
  }).handleError((error, stack) {
    _logger.error('Error in watchById stream for $T:$id: $error', stack);
    // Don't rethrow - let the stream continue
  });
}