syncPendingMutations method

Future<void> syncPendingMutations()

Implementation

Future<void> syncPendingMutations() async {
  if (_disposed) return;
  if (_isSyncing) {
    SdkLogger.d('Sync already in progress, skipping');
    return;
  }
  if (_connection.state is! Connected) {
    SdkLogger.d('syncPendingMutations: not connected, skipping');
    return;
  }

  SdkLogger.d('syncPendingMutations: starting');
  _isSyncing = true;
  final cycleFailures = <MutationSyncResult>[];

  try {
    final pending = await _storage.getPendingMutations();
    if (pending.isEmpty) {
      SdkLogger.d('syncPendingMutations: no pending mutations, setting idle');
      _cachedPendingCount = 0;
      _updateSyncState(
        _currentSyncState.copyWith(status: SyncStatus.idle, pendingCount: 0),
      );
      return;
    }

    _cachedPendingCount = pending.length;
    _updateSyncState(
      _currentSyncState.copyWith(
        status: SyncStatus.syncing,
        pendingCount: _cachedPendingCount,
      ),
    );

    SdkLogger.d('Syncing ${pending.length} pending mutations');

    for (final mutation in pending) {
      final step = await _processMutation(mutation, cycleFailures);
      if (step == _SyncStep.stop) return;
      if (step == _SyncStep.pauseQueue) break;
    }
  } finally {
    _isSyncing = false;
    SdkLogger.d('syncPendingMutations: finished (isSyncing=false)');
  }

  if (_disposed) {
    SdkLogger.d(
      'syncPendingMutations: disposed, skipping final state update',
    );
    return;
  }

  await _finalizeSyncCycle(cycleFailures);
}