Recipes
A profile with a TTL cache
Serve fresh or stale profiles and retain usable data when the network or a cache write fails.
Full program: ttl_cache_recipe.dart.
Useful when a previously fetched profile should open quickly but eventually
refresh. _ProfileCache and _ProfileRemote are separate typed contracts.
Decide freshness explicitly
The constructor receives a user ID, a positive TTL and a clock function. A value is fresh when its age is nonnegative and less than the TTL. At exactly five minutes, the five-minute example cache is stale. A future timestamp after a clock change is not treated as proof of freshness. No real timer or waiting is needed to demonstrate expiry: the example advances its injected clock.
Follow load()
- Read the cache for the requested user. A record for another user is an adapter error, not permission to display that user's profile. Blank fields are also rejected before publication.
- Publish a fresh cached value and return without accessing the remote source.
- If the value is stale, publish it with
isStale: true, then request a refresh. The view can keep usable content visible while the caller awaitsload(). - Normalize the remote record and publish fresh domain data.
- Write that record and its fetch timestamp to the cache.
Concurrent calls share the whole load operation, including cache access. The
domain snapshot reports whether data came from empty, cache, remote or
memory; it does not expose the source DTO or the source instances.
There are two different failures
- Network failure:
load()fails and the stale profile remains available. The caller decides when to retry or how to present the error. - Cache write failure after a successful response:
load()still reports the write error, but the fresh profile remains in memory. Losing persistence is not the same as failing to obtain usable data. A later load prefers this unpersisted fresh value over an older cache record; it does not roll the profile back. Once that in-memory value expires, the next successful refresh attempts persistence again. It is not a separate immediate “retry cache write” API.
This policy is a deliberate trade-off. An application that must guarantee an offline copy before displaying new data should persist first, then publish, as the next example does. Cache read failures propagate rather than silently becoming misses. The example does not add background retries, cross-account cache invalidation, encryption, eviction or a general caching service to the package.
Repository implementation
The Repository below is taken from the runnable program linked above. That file also contains its domain types, imports, source adapters and executable checks; this excerpt is not a separate standalone program.
final class _ProfileRepository extends Repository<_ProfileData> {
_ProfileRepository({
required super.dataSources,
required final String userId,
required this.now,
required final Duration ttl,
}) : _cache = dataSources.get<_ProfileCache>(),
_remote = dataSources.get<_ProfileRemote>(),
_userId = userId.trim(),
_ttl = ttl,
super(
initialData: const _ProfileData(null, _Origin.empty, isStale: true),
) {
if (_userId.isEmpty) throw ArgumentError.value(userId, 'userId');
if (ttl <= Duration.zero) throw ArgumentError.value(ttl, 'ttl');
}
final _ProfileCache _cache;
final _ProfileRemote _remote;
final String _userId;
final DateTime Function() now;
final Duration _ttl;
Future<void>? _pending;
_CachedProfile? _unpersisted;
Future<void> load() {
if (isClosed) throw RepositoryClosedException(runtimeType);
final Future<void>? pending = _pending;
if (pending != null) return pending;
final Future<void> operation = _load().whenComplete(() => _pending = null);
_pending = operation;
return operation;
}
Future<void> _load() async {
final _CachedProfile? cached = await _cache.read(_userId);
if (isClosed) return;
// Even an older cache must belong to this user. Do not hide a broken
// adapter simply because an in-memory value is available.
if (cached != null) _normalize(cached.record);
final _CachedProfile? memory = _unpersisted;
final bool useMemory =
memory != null &&
(cached == null || !cached.fetchedAt.isAfter(memory.fetchedAt));
final _CachedProfile? candidate = useMemory ? memory : cached;
if (candidate != null) {
final _Profile profile = _normalize(candidate.record);
final Duration age = now().difference(candidate.fetchedAt);
// A future timestamp (clock moved backwards) is not proof of freshness.
final bool fresh = age >= Duration.zero && age < _ttl;
setData(
_ProfileData(
profile,
useMemory ? _Origin.memory : _Origin.cache,
isStale: !fresh,
),
);
if (fresh) return;
}
final _ProfileRecord record = await _remote.fetch(_userId);
if (isClosed) return;
final _Profile profile = _normalize(record);
final DateTime fetchedAt = now();
setData(_ProfileData(profile, _Origin.remote, isStale: false));
// Policy choice: usable network data is published even if persistence
// fails. The caller still receives the cache write error through load().
final _CachedProfile recordToCache = _CachedProfile(
_ProfileRecord(profile.id, profile.name),
fetchedAt,
);
_unpersisted = recordToCache;
await _cache.write(_userId, recordToCache);
_unpersisted = null;
}
_Profile _normalize(final _ProfileRecord record) {
final String id = record.id.trim();
final String name = record.name.trim();
if (id.isEmpty || id != _userId || name.isEmpty) {
throw const FormatException('Expected the requested user and a name.');
}
return _Profile(id, name);
}
}
Closing and ownership in all recipes
Sources are constructed by the composition scope and resolved once through
DataSourceContainer. Repositories never close those borrowed sources.
Closing invalidates later publication, not the underlying external operation. A network write may still take effect after the Repository closes. The sync example leaves the request in the outbox so the next coordinator can recover its receipt. A local transaction already in progress may still complete; queued work that has not started is rejected after close. Await outstanding operation Futures and handle their errors before closing the sources that serve them.
The pagination subscriber remains unpaused through close() to receive all
committed states and done. In error cleanup it cancels its own subscription
first. Do not infer that every foreign/paused subscription can always be drained
by a deadline: see stream and lifecycle.
For additional subscription assertions, the published ark_data_layer_test companion observes a Repository without taking ownership. The examples here deliberately use only the runtime package and standard Dart libraries.