withSubscriptionEvent method
Returns a new QuerySnapshot with the event
applied
Takes the existing snapshots QueryPredicate and QuerySortBy conditions into consideration when applying the event
If the event
does not result in a change to the QuerySnapshot,
the current snapshot is returned
Implementation
QuerySnapshot<T> withSubscriptionEvent({
required SubscriptionEvent<T> event,
}) {
SortedList<T> sortedListCopy = SortedList.from(_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;
}