noStructuralSharing<TQueryData> function

StructuralSharing<TQueryData> noStructuralSharing<TQueryData>()

The opt-out for QueryOptions.structuralSharing: every write keeps the incoming value, so every refetch reports a new instance, and so does every select. TanStack Query spells this structuralSharing: false.

QueryOptions<List<Task>>(
  queryKey: QueryKey(['tasks']),
  queryFn: fetchTasks,
  structuralSharing: noStructuralSharing(),
);

Use this rather than an equivalent (_, next) => next of your own. The two behave identically where they are called — on the cache write and on unselected placeholder data — but only this one is recognised as the opt-out, and that is what turns sharing off for a select's output too: no hook typed on the query's data can be handed a selection of another type, so a hook of your own leaves the selection shared by the default walk.

A call rather than a function to pass: it returns one hook per TQueryData, the same instance every time, so options built with it compare equal across rebuilds. Recognition is by that instance's identity.

Implementation

StructuralSharing<TQueryData> noStructuralSharing<TQueryData>() {
  // Memoised instances rather than a generic tear-off compared by `==`: on
  // the VM, `f<T>` instantiated inside a generic class is not `==` to the
  // `f<String>` a caller passed, even when `T` is `String`.
  final existing = _noStructuralSharingHooks[TQueryData];
  if (existing != null) {
    return existing as StructuralSharing<TQueryData>;
  }
  TQueryData keepNext(TQueryData? previous, TQueryData next) => next;
  final StructuralSharing<TQueryData> hook = keepNext;
  _noStructuralSharingHooks[TQueryData] = hook;
  _noStructuralSharingInstances.add(hook);
  return hook;
}