callOnceWhenReady<T> method

void callOnceWhenReady<T>({
  1. required VoidCallback callback,
  2. required ValueListenable<T> trigger,
  3. required bool readyWhen(
    1. T triggerValue
    ),
})

Runs callback when trigger's value satisfies the readyWhen function.

When calling callOnceWhenReady : - If trigger's value satisfies readyWhen, then the callback will be immediately triggered. - Otherwise, the callback will be triggered when trigger's value changes to equal readyWhen.

Any listeners set by callOnceWhenReady will auto dispose, or be removed after the callback is run.

Implementation

void callOnceWhenReady<T>({
  required VoidCallback callback,
  required ValueListenable<T> trigger,
  required bool Function(T triggerValue) readyWhen,
}) {
  if (readyWhen(trigger.value)) {
    callback();
  } else {
    VoidCallback? triggerListener;
    triggerListener = () {
      if (readyWhen(trigger.value)) {
        callback();
        trigger.removeListener(triggerListener!);

        _listenables.remove(trigger);
        _listeners.remove(triggerListener);
      }
    };
    addAutoDisposeListener(trigger, triggerListener);
  }
}