ServiceList<Id, Data> constructor

ServiceList<Id, Data>(Service<Id, Data> service, { String idField: 'id', Equality<Data> equality })

Implementation

ServiceList(this.service, {this.idField = 'id', Equality<Data> equality})
    : super([]) {
  _equality = equality;
  _equality ??= new EqualityBy<Data, Id>((map) {
    if (map is Map)
      return map[idField ?? 'id'] as Id;
    else
      throw new UnsupportedError(
          'ServiceList only knows how to find the id from a Map object. Provide a custom `Equality` in your call to the constructor.');
  });
  // Index
  _subs.add(service.onIndexed.where(_notNull).listen((data) {
    this
      ..clear()
      ..addAll(data);
    _onChange.add(this);
  }));

  // Created
  _subs.add(service.onCreated.where(_notNull).listen((item) {
    add(item);
    _onChange.add(this);
  }));

  // Modified/Updated
  handleModified(Data item) {
    var indices = <int>[];

    for (int i = 0; i < length; i++) {
      if (_equality.equals(item, this[i])) indices.add(i);
    }

    if (indices.isNotEmpty) {
      for (var i in indices) this[i] = item;

      _onChange.add(this);
    }
  }

  _subs.addAll([
    service.onModified.where(_notNull).listen(handleModified),
    service.onUpdated.where(_notNull).listen(handleModified),
  ]);

  // Removed
  _subs.add(service.onRemoved.where(_notNull).listen((item) {
    removeWhere((x) => _equality.equals(item, x));
    _onChange.add(this);
  }));
}