cached<T> static method

Computed<T> cached<T>(
  1. T compute(), {
  2. 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;
    },
  );
}