memoize
Caches a unary function's results, keyed by its argument.
Lecture
memoize(f) wraps f in a cache: the first time
it's called with a given argument, it runs f and remembers
the result; every later call with an ==-equal argument
returns the cached result instantly, without calling f
again. Reach for it when f is expensive (heavy computation,
a network call) and is likely to be called repeatedly with the same
inputs.
FxDart's memoize is unary only and keys the
cache by the argument's ==/hashCode. FxTS's
version is variadic and keys on the full argument list via a
WeakMap-backed cache — Dart has no direct equivalent (no
variadic generics, and WeakMap-style weak keys aren't
available for arbitrary objects), so multi-argument functions need to be
memoized on a single composite key (a record works well) instead.
Because R is unconstrained, f can return a
Future — memoizing an async operation caches the
Future itself, so a second call returns an already-completed
future immediately rather than re-running the work.
Demo 1 · Basics
Demo 2 · Memoizing an async lookup
The second call to fetchUser(1) returns the cached,
already-completed Future — no 150ms wait:
Try it yourself
Exercise: wrap this "slow" cubing function with memoize so
that calling it twice with 3 only runs the real computation once.
delay & sleep — used above to simulate a slow async call ·
debounce — rate-limit calls instead of caching them ·
identity — the simplest possible function to wrap ·
always — a constant value, no caching needed