useValueListener<T> function

void useValueListener<T>(
  1. ValueListenable<T>? listenable, {
  2. required bool callInitially,
  3. required ValueCallback<T> callback,
})

Adds callback as listener to listenable and removes it again upon destruction of the hook. If called multiple times with different callbacks, the one from the most recent call will be used.

If callInitially is true, the callback is called immediately, otherwise the callback is called when the listenable is notified without triggering a build of the HookWidget.

Consider this as an alterntive to useValueListenable if you want to avoid the HookWidget to rebuild.

See: useListener

Implementation

void useValueListener<T>(
  ValueListenable<T>? listenable, {
  required bool callInitially,
  required ValueCallback<T> callback,
}) {
  // store the latest version of `callback`
  final callbackHolder = useVariable(callback)..value = callback;

  useEffect(
    () {
      if (listenable == null) {
        return null;
      }
      void lcallback() => callbackHolder.value(listenable.value);

      listenable.addListener(lcallback);
      if (callInitially) {
        callback(listenable.value);
      }
      return () => listenable.removeListener(lcallback);
    },
    [listenable],
  );
}