updateWhereEmit method

  1. @override
int updateWhereEmit(
  1. bool matcher(
    1. T item
    ),
  2. T updater(
    1. T item
    )
)
override

Updates all items that match the predicate. Returns the number of items updated.

Implementation

@override
int updateWhereEmit(
    bool Function(T item) matcher, T Function(T item) updater) {
  final currentState = state;
  if (currentState is! SmartPaginationLoaded<T>) return 0;

  final updated = List<T>.from(currentState.allItems);
  final order = _orders?.activeOrder;
  var updateCount = 0;

  if (order != null) {
    // Collect items to update
    final itemsToUpdate = <T>[];
    final indicesToRemove = <int>[];

    for (var i = 0; i < updated.length; i++) {
      if (matcher(updated[i])) {
        itemsToUpdate.add(updater(updated[i]));
        indicesToRemove.add(i);
        updateCount++;
      }
    }

    if (updateCount == 0) return 0;

    // Remove items in reverse order to maintain indices
    for (var i = indicesToRemove.length - 1; i >= 0; i--) {
      updated.removeAt(indicesToRemove[i]);
    }

    // Re-insert updated items at correct sorted positions using merge
    final result = _insertAllSorted(updated, itemsToUpdate);
    updated
      ..clear()
      ..addAll(result);
  } else {
    // No sorting, update in place
    for (var i = 0; i < updated.length; i++) {
      if (matcher(updated[i])) {
        updated[i] = updater(updated[i]);
        updateCount++;
      }
    }

    if (updateCount == 0) return 0;
  }

  _onInsertionCallback?.call(updated);

  _refreshDataAge();
  emit(
    currentState.copyWith(
      allItems: updated,
      items: updated,
      lastUpdate: DateTime.now(),
      fetchedAt: _lastFetchTime,
      dataExpiredAt: _getDataExpiredAt(),
    ),
  );
  return updateCount;
}