getOrCreateNode<T> method

ZenithNode<T> getOrCreateNode<T>(
  1. NodeKey key,
  2. T factory(
    1. ZenithRef ref
    )
)

Retrieves or creates a node identified by key.

If a node for key already exists, returns the cached instance (cast to ZenithNode<T>). Otherwise, invokes factory with a fresh ZenithRef to produce the initial value, wraps it in a ZenithNode, caches it, and returns it.

Throws StateError if the container has been disposed.

Implementation

ZenithNode<T> getOrCreateNode<T>(
  NodeKey key,
  T Function(ZenithRef ref) factory,
) {
  if (_isDisposed) {
    throw StateError('Cannot create node in disposed ZenithContainer');
  }

  _assertCaptiveDependencyAllowed(key);

  final existing = _nodes[key];
  if (existing != null) {
    return existing as ZenithNode<T>;
  }

  final ref = ZenithRef(this);
  _refs[key] = ref;

  final T initialValue;
  try {
    initialValue = factory(ref);
  } catch (_) {
    ref._dispose();
    _activeRefs.remove(ref);
    _refs.remove(key);
    rethrow;
  }

  final node = ZenithNode<T>(initialValue);
  _nodes[key] = node;
  return node;
}