syncWorker function

  1. @Riverpod(keepAlive: true)
SyncWorker? syncWorker(
  1. Ref<Object?> ref
)

Background drain worker that replays the OfflineOutbox into Supabase on every online tick from isOnlineProvider. null on web.

Implementation

@Riverpod(keepAlive: true)
SyncWorker? syncWorker(Ref ref) {
  if (kIsWeb) return null;
  final outbox = ref.watch(offlineOutboxProvider);
  if (outbox == null) return null;
  final worker = SyncWorker(outbox, ref.watch(supabaseDatasourceProvider));
  // Trigger a drain on first online value and on every online→true
  // transition. `ref.listen` doesn't refire for equal values, so a flaky
  // connection that re-asserts `true` shouldn't trigger redundant
  // drains; if it does, [SyncWorker._draining] is the re-entrant guard.
  ref.listen<AsyncValue<bool>>(isOnlineProvider, (_, next) {
    if (next.valueOrNull == true) {
      unawaited(worker.drain());
    }
  }, fireImmediately: true);
  ref.onDispose(() => unawaited(worker.stop()));
  return worker;
}