syncWith method

Future<void> syncWith(
  1. DataCacheX remoteCache, {
  2. Set<String>? keys,
  3. CachePolicy? policy,
  4. bool bidirectional = false,
  5. ConflictResolution conflictResolution = ConflictResolution.newerWins,
})

Synchronizes the primary cache with the given remote cache.

If keys is provided, only the specified keys will be synchronized. If policy is provided, it will be used for all items during synchronization. If bidirectional is true, changes will be synchronized in both directions. If conflictResolution is provided, it will be used to resolve conflicts.

Implementation

Future<void> syncWith(
  DataCacheX remoteCache, {
  Set<String>? keys,
  CachePolicy? policy,
  bool bidirectional = false,
  ConflictResolution conflictResolution = ConflictResolution.newerWins,
}) async {
  try {
    _syncController.add(CacheSyncEvent.syncStarted());
    _log.info('Starting cache synchronization');

    // Get all keys from both caches
    final primaryKeys = await _getAllKeys(_primaryCache);
    final remoteKeys = await _getAllKeys(remoteCache);

    // Determine which keys to synchronize
    final keysToSync = keys ?? {...primaryKeys, ...remoteKeys};

    // Process keys in batches to avoid memory issues
    const batchSize = 50;
    final keysList = keysToSync.toList();

    for (var i = 0; i < keysList.length; i += batchSize) {
      final end =
          (i + batchSize < keysList.length) ? i + batchSize : keysList.length;
      final batch = keysList.sublist(i, end);

      await _syncBatch(
        batch,
        remoteCache,
        policy: policy,
        bidirectional: bidirectional,
        conflictResolution: conflictResolution,
      );
    }

    _syncController.add(CacheSyncEvent.syncCompleted());
    _log.info('Cache synchronization completed');
  } catch (e) {
    _syncController.add(CacheSyncEvent.error(e));
    _log.severe('Error during cache synchronization: $e');
    rethrow;
  }
}