cached<T> static method
- T compute(), {
- Duration? ttl,
Create a signal that caches computed values.
The ttl (time-to-live) parameter specifies how long the cached value
remains valid before recomputation.
Implementation
static Computed<T> cached<T>(
T Function() compute, {
Duration? ttl,
}) {
T? cache;
DateTime? cacheTime;
return Computed<T>(
() {
final now = DateTime.now();
if (cache != null &&
cacheTime != null &&
ttl != null &&
now.difference(cacheTime!) < ttl) {
return cache as T;
}
cache = compute();
cacheTime = now;
return cache as T;
},
);
}