MapsObjectUpdates<T extends MapsObject>.from constructor

MapsObjectUpdates<T extends MapsObject>.from(
  1. Set<T> previous,
  2. Set<T> current, {
  3. required String objectName,
})

Computes updates given previous and current object sets.

objectName is the prefix to use when serializing the updates into a JSON dictionary. E.g., 'circle' will give 'circlesToAdd', 'circlesToUpdate', 'circleIdsToRemove'.

Implementation

MapsObjectUpdates.from(
  Set<T> previous,
  Set<T> current, {
  required this.objectName,
}) {
  final Map<MapsObjectId<T>, T> previousObjects = keyByMapsObjectId(previous);
  final Map<MapsObjectId<T>, T> currentObjects = keyByMapsObjectId(current);

  final Set<MapsObjectId<T>> previousObjectIds = previousObjects.keys.toSet();
  final Set<MapsObjectId<T>> currentObjectIds = currentObjects.keys.toSet();

  /// Maps an ID back to a [T] in [currentObjects].
  ///
  /// It is a programming error to call this with an ID that is not guaranteed
  /// to be in [currentObjects].
  T _idToCurrentObject(MapsObjectId<T> id) {
    return currentObjects[id]!;
  }

  _objectIdsToRemove = previousObjectIds.difference(currentObjectIds);

  _objectsToAdd = currentObjectIds
      .difference(previousObjectIds)
      .map(_idToCurrentObject)
      .toSet();

  // Returns `true` if [current] is not equals to previous one with the
  // same id.
  bool hasChanged(T current) {
    final T? previous = previousObjects[current.mapsId as MapsObjectId<T>];
    return current != previous;
  }

  _objectsToChange = currentObjectIds
      .intersection(previousObjectIds)
      .map(_idToCurrentObject)
      .where(hasChanged)
      .toSet();
}