GlucoseSetup.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import CoreData
  2. import Foundation
  3. extension Home.StateModel {
  4. func setupGlucoseArray() {
  5. Task {
  6. do {
  7. let ids = try await self.fetchGlucose()
  8. let glucoseObjects: [GlucoseStored] = try await CoreDataStack.shared
  9. .getNSManagedObject(with: ids, context: viewContext)
  10. await updateGlucoseArray(with: glucoseObjects)
  11. } catch {
  12. debug(
  13. .default,
  14. "\(DebuggingIdentifiers.failed) Error setting up glucose array: \(error)"
  15. )
  16. }
  17. }
  18. }
  19. private func fetchGlucose() async throws -> [NSManagedObjectID] {
  20. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  21. ofType: GlucoseStored.self,
  22. onContext: glucoseFetchContext,
  23. predicate: NSPredicate.glucose,
  24. key: "date",
  25. ascending: true,
  26. batchSize: 50
  27. )
  28. return try await glucoseFetchContext.perform {
  29. guard let fetchedResults = results as? [GlucoseStored] else {
  30. throw CoreDataError.fetchError(function: #function, file: #file)
  31. }
  32. // Update Main Chart Y Axis Values
  33. // Perform everything on "context" to be thread safe
  34. self.yAxisChartData(glucoseValues: fetchedResults)
  35. return fetchedResults.map(\.objectID)
  36. }
  37. }
  38. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  39. glucoseFromPersistence = objects
  40. latestTwoGlucoseValues = Array(objects.suffix(2))
  41. }
  42. }