weakAtomFamily<A extends Atom, Arg> function

A Function(Arg arg) weakAtomFamily<A extends Atom, Arg>(
  1. A create(
    1. Arg arg
    )
)

Alternate version of atomFamily that holds a weak reference to each child.

Implementation

A Function(Arg arg) weakAtomFamily<A extends Atom, Arg>(
  A Function(Arg arg) create,
) {
  final atoms = HashMap<Arg, WeakReference<A>>();

  return (arg) {
    final atom = atoms[arg]?.target;
    if (atom != null) {
      return atom;
    }

    final newAtom = create(arg);
    atoms[arg] = WeakReference(newAtom);
    return newAtom;
  };
}