dependent<A, B> static method

ComputedCachedValue<A, B> dependent<A, B>({
  1. required ComputeCacheDependency<B> on,
  2. required ComputeCacheCallback<A> compute,
})

Creates a CachedValue that its validity is defined by a dependency.

This cache type will be considered invalid if the overall returned value of the dependency callback changes since the last refresh.

Besides dependency change, this cache can also be manually updated on marked as invalid via refresh and invalidate.

Usage example:

int factorial(int n) {
  if (n < 0) throw ('Negative numbers are not allowed.');
  return n <= 1 ? 1 : n * factorial(n - 1);
}

int originalValue = 1;
final factorialCache = CachedValue.dependent(
  on: () => originalValue,
  compute: () => factorial(originalValue),
);
print(factorialCache.value); // 1

originalValue = 6;
print(factorialCache.value); // 720

The dependency callback on is called on every value access. So it is recommended to keep the dependency callback as declarative as possible.

See also:

Implementation

static ComputedCachedValue<A, B> dependent<A, B>({
  required ComputeCacheDependency<B> on,
  required ComputeCacheCallback<A> compute,
}) {
  return ComputedCachedValue<A, B>(on, compute);
}