fxMemoizeLast
Remembers only the last call — and recognises a repeat by identity, in O(1).
Lecture
fxMemoize keeps every argument
it has ever seen, keyed by ==/hashCode. That is
wrong for the most common thing an app wants to cache: a value derived
from immutable state. Every change makes a new state
object, so a memo over state grows by one entry per change, forever —
and hashing a large state on every call can cost more than the work it
saves.
fxMemoizeLast(f) keeps one slot. A call whose argument is
identical to the previous call's returns the previous
result; anything else runs f and replaces the slot. With
immutable state that is exactly right: the same instance means nothing
changed, a new instance means something might have, and the test is a
pointer compare. A widget that rebuilds sixty times a second over the
same state pays for f once.
Pass equals to compare by value instead, or to key on a
record — (state, id) compared field by field — when the
function takes more than one argument. Only memoize a function whose
result depends on its argument alone: one that also reads the clock or
a mutable field will serve a stale answer from the slot. fxdart
extension (not part of FxTS), after reselect's selector memo.
Demo 1 · Same state, one run
Demo 2 · Two arguments, and versus fxMemoize
Try it yourself
Exercise: make three calls on the same list run the function once.
fxMemoize — a cache of every argument ·
fxOnChange — skip a callback whose value did not change ·
fxIdentity