subscribe method

ZenithSubscription subscribe(
  1. ZenithSubscriber subscriber
)

Adds subscriber to this node's listener set.

The subscriber is held via a WeakReference and is deduplicated by identity — subscribing the same instance multiple times is a no-op.

Throws StateError if the node has been disposed.

Implementation

ZenithSubscription subscribe(ZenithSubscriber subscriber) {
  if (_isDisposed) {
    throw StateError('Cannot subscribe to a disposed ZenithNode');
  }

  final entry = _SubscriberEntry(WeakReference<ZenithSubscriber>(subscriber));
  if (_tail == null) {
    _head = _tail = entry;
  } else {
    _tail!.next = entry;
    entry.prev = _tail;
    _tail = entry;
  }
  _subscriberCount++;

  bool isCancelled = false;
  return () {
    if (isCancelled || _isDisposed) return;
    isCancelled = true;

    if (entry.prev != null) {
      entry.prev!.next = entry.next;
    } else {
      _head = entry.next;
    }

    if (entry.next != null) {
      entry.next!.prev = entry.prev;
    } else {
      _tail = entry.prev;
    }

    _subscriberCount--;
  };
}