watchUser method

Stream<User?> watchUser()

Gets the current user with automatic cache refresh. Watches the current user with automatic background refresh.

Emits null when not logged in. Emits stale data immediately, then triggers a background network fetch if stale. The stream re-emits automatically when the DB is updated.

Network errors during background refresh are absorbed — the stream continues showing stale data rather than erroring.

Implementation

Stream<User?> watchUser() async* {
  const ttl = Duration(days: 3);

  await for (final user
      in _database.select(_database.users).watchSingleOrNull()) {
    yield user;
    if (user == null) continue;

    final age = switch (user.fetchedAt) {
      final t? => DateTime.now().difference(t),
      null => ttl,
    };
    if (age >= ttl) {
      try {
        await refreshUser();
      } catch (_) {
        // Absorb: stale data is shown via stream
      }
    }
  }
}