remember<T> method

Future<T> remember<T>(
  1. String key,
  2. Duration? duration,
  3. FutureOr<T> compute(), {
  4. T decode(
    1. Object? json
    )?,
  5. bool lock = false,
})

The cached value, or run compute and store the result. The value is stored as JSON, so return maps, lists, strings and numbers, not models:

List<dynamic> posts = await Cache().remember(
  'posts',
  Duration(minutes: 5),
  () async => (await Post().all()).map((Post p) => p.toJson()).toList(),
);

decode turns the stored JSON back into T on a cache hit, eg. decode: (Object? j) => (j as List<dynamic>).cast<String>(). Without it, T must be a JSON type like List<dynamic>. With lock, only one caller on all isolates and servers runs compute. The others wait for its value.

Implementation

Future<T> remember<T>(
  String key,
  Duration? duration,
  FutureOr<T> Function() compute, {
  T Function(Object? json)? decode,
  bool lock = false,
}) {
  return repository.remember<T>(
    key,
    duration,
    compute,
    decode: decode,
    lock: lock,
  );
}