Speed up HealthKit sync with batch saves

Save 100 samples at a time instead of individually. Removes per-entry
delays and uses healthStore.save([batch]) for much faster throughput.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Trey t
2025-12-20 01:03:06 -06:00
parent 4fbefd86fb
commit 5950ca738b

View File

@@ -126,25 +126,36 @@ class HealthKitManager: ObservableObject {
return
}
// Create all samples upfront
let samples: [HKStateOfMind] = validEntries.map { entry in
HKStateOfMind(
date: entry.forDate,
kind: .dailyMood,
valence: moodToValence(entry.mood),
labels: labelsForMood(entry.mood),
associations: [.currentEvents]
)
}
// Save in batches for better performance
let batchSize = 100
var successCount = 0
var failCount = 0
for (index, entry) in validEntries.enumerated() {
for batchStart in stride(from: 0, to: samples.count, by: batchSize) {
let batchEnd = min(batchStart + batchSize, samples.count)
let batch = Array(samples[batchStart..<batchEnd])
do {
try await saveMood(entry.mood, for: entry.forDate, note: entry.notes)
successCount += 1
try await healthStore.save(batch)
successCount += batch.count
} catch {
failCount += 1
logger.error("Failed to sync mood for \(entry.forDate): \(error.localizedDescription)")
failCount += batch.count
logger.error("Failed to sync batch starting at \(batchStart): \(error.localizedDescription)")
}
syncedCount = index + 1
syncedCount = batchEnd
syncProgress = Double(syncedCount) / Double(totalToSync)
// Add a small delay to avoid overwhelming HealthKit
if index % 10 == 0 && index > 0 {
try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
}
}
isSyncing = false