notifyListeners method

void notifyListeners()

Manually notifies all listeners.

Use this if you need to trigger updates even if the value hasn't changed, or if the value is mutable and has been modified internally.

Implementation

void notifyListeners() {
  assert(!_hasFlag(_flagDisposed),
      'Cannot notify listeners on a disposed NeuronAtom');
  if (_hasFlag(_flagDisposed)) return;
  if (_listeners.isEmpty) return;

  // If inside a batch, defer notification until the batch completes
  if (NeuronBatch.isBatching) {
    NeuronBatch.defer(this);
    return;
  }

  // Track if listeners are modified during notification
  bool listenersModified = false;
  final originalLength = _listeners.length;

  // Iterate with index to avoid allocation when no modification occurs
  for (int i = 0; i < _listeners.length; i++) {
    // Check if listeners were modified (added/removed)
    if (_listeners.length != originalLength) {
      listenersModified = true;
    }

    // If modified, switch to safe copy-based iteration for remaining listeners
    if (listenersModified) {
      final remaining = List<AtomListener>.from(_listeners.skip(i));
      for (final listener in remaining) {
        try {
          if (_listeners.contains(listener)) {
            listener.invoke();
          }
        } catch (e, st) {
          neuronErrorHandler('Error in NeuronAtom listener', e, st);
        }
      }
      break;
    }

    try {
      _listeners[i].invoke();
    } catch (e, st) {
      neuronErrorHandler('Error in NeuronAtom listener', e, st);
    }
  }
}