add method

Future<Capability> add(
  1. T element,
  2. {Iterable? tags}
)

Adds element to the registry with the provided tags.

Fails if element is already in this registry. An object is already in the registry if it has been added using add, or if it was returned by a lookup call on this registry object.

Returns a capability that can be used with remove to remove the element from the registry again.

The tags can be used to distinguish some of the elements from other elements. Any object can be used as a tag, as long as it preserves equality when sent through a SendPort. This makes Capability objects a good choice for tags.

Implementation

Future<Capability> add(T element, {Iterable? tags}) {
  var cache = _cache;
  if (cache.contains(element)) {
    return Future<Capability>.sync(() {
      throw StateError(
          'Object already in registry: ${Error.safeToString(element)}');
    });
  }
  var completer = Completer<Capability>();
  var port = singleCompletePort(completer,
      callback: (List<Object?> response) {
        assert(cache.isAdding(element));
        var id = response[0] as int;
        var removeCapability = response[1] as Capability;
        cache.register(id, element);
        return removeCapability;
      },
      timeout: _timeout,
      onTimeout: () {
        cache.stopAdding(element);
        throw TimeoutException('Future not completed', _timeout);
      });
  if (tags != null) tags = tags.toList(growable: false);
  cache.setAdding(element);
  _commandPort.send(list4(_addValue, element, tags, port));
  return completer.future;
}