QuerySnapshot withSubscriptionEvent()

in packages/amplify_datastore_plugin_interface/lib/src/types/models/query_snapshot.dart [89:131]


  QuerySnapshot<T> withSubscriptionEvent({
    required SubscriptionEvent<T> event,
  }) {
    SortedList<T> sortedListCopy = SortedList.from(this._sortedList);
    SortedList<T>? updatedSortedList;

    T newItem = event.item;
    bool newItemMatchesPredicate = where == null || where!.evaluate(newItem);
    int currentItemIndex =
        sortedListCopy.indexWhere((item) => item.getId() == newItem.getId());
    T? currentItem =
        currentItemIndex == -1 ? null : sortedListCopy[currentItemIndex];
    bool currentItemMatchesPredicate =
        currentItem != null && (where == null || where!.evaluate(currentItem));

    if (event.eventType == EventType.create &&
        newItemMatchesPredicate &&
        currentItem == null) {
      updatedSortedList = sortedListCopy..addSorted(newItem);
    } else if (event.eventType == EventType.delete && currentItem != null) {
      updatedSortedList = sortedListCopy..removeAt(currentItemIndex);
    } else if (event.eventType == EventType.update) {
      if (currentItemMatchesPredicate &&
          newItemMatchesPredicate &&
          currentItem != newItem) {
        updatedSortedList = sortedListCopy
          ..updateAtSorted(currentItemIndex, newItem);
      } else if (currentItemMatchesPredicate && !newItemMatchesPredicate) {
        updatedSortedList = sortedListCopy..removeAt(currentItemIndex);
      } else if (currentItem == null && newItemMatchesPredicate) {
        updatedSortedList = sortedListCopy..addSorted(newItem);
      }
    }
    if (updatedSortedList != null) {
      return QuerySnapshot._(
        sortedList: updatedSortedList,
        isSynced: isSynced,
        where: where,
        sortBy: sortBy,
      );
    }
    return this;
  }