Files
minstrel/flutter_client/lib/cache/cache_first.dart
T
bvandeusen 94727f40bb fix(flutter): analyze errors after Plan C provider migrations
- cache_first.dart: backtick-fence List<T> doc comment to dodge
  unintended_html_in_doc_comment.
- library_providers.dart:163: switch single-row insert to
  insertAllOnConflictUpdate; Batch only exposes the *AllOnConflict*
  variant.
- 5 test files: StreamProvider.overrideWith takes Create<Stream<T>>,
  not Create<Future<T>>. Wrap data emissions in Stream.value(...).
- artist_detail_screen_test: add models/album.dart import for AlbumRef
  type annotation.
- track_actions_sheet_test: drop _StubLiked extends LikedIdsController
  (notifier no longer exists post-migration); override with
  Stream.value(LikedIds(...)) instead.
- like_button_test: rollback assertion now requires drift writes via
  LikesController. Skip under _skipDrift until libsqlite3-dev lands on
  the runner image (Fable #399). Replace stale .notifier reference
  with likesControllerProvider for completeness.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 13:04:27 -04:00

50 lines
1.9 KiB
Dart

// Drift-first reactive read pattern with REST cold-cache fallback (#357 plan C).
//
// Subscribes to a drift watch() stream. On each emission:
// - non-empty → map to result type T and yield
// - empty + online → fetch via REST, populate drift, await re-emission
// - empty + offline → yield mapped empty result (UI shows empty state)
//
// The pattern lets every read provider trust drift as the source of
// truth. SyncController keeps drift fresh in the background; widget
// rebuilds happen automatically as drift writes propagate via watch().
import 'dart:async';
/// Wraps the watch + cold-cache fallback pattern. Generic over:
/// D — the drift row type (or TypedResult for joins)
/// T — the result type the caller wants (e.g. `List<ArtistRef>`)
///
/// `fetchAndPopulate` is invoked when drift is empty AND `isOnline()`
/// returns true. It must populate drift via its own side-effect; the
/// drift watch() stream will re-emit and this helper yields the
/// populated rows on the next iteration.
///
/// REST failures are swallowed — the helper falls through to yielding
/// the empty result. Caller is responsible for surfacing errors via
/// toast etc.
Stream<T> cacheFirst<D, T>({
required Stream<List<D>> driftStream,
required Future<void> Function() fetchAndPopulate,
required T Function(List<D>) toResult,
required Future<bool> Function() isOnline,
}) async* {
await for (final rows in driftStream) {
if (rows.isNotEmpty) {
yield toResult(rows);
continue;
}
if (await isOnline()) {
try {
await fetchAndPopulate();
// The drift watch() stream re-emits with the populated rows on
// the next loop iteration. Don't yield here.
} catch (_) {
yield toResult(rows); // empty result; caller surfaces error
}
} else {
yield toResult(rows); // empty result; offline
}
}
}