From 985e8ffe8ea9d9774738cba64534bd44bea260b3 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Wed, 12 Apr 2023 16:34:28 +0200 Subject: [PATCH] Implemented the "loadLocations()" function in the LocationsListViewModel view model. --- .../LocationsListViewModel.swift | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Apps/Locations/Sources/Screens/LocationsList/LocationsListViewModel.swift b/Apps/Locations/Sources/Screens/LocationsList/LocationsListViewModel.swift index 6b4f55d..7b68701 100644 --- a/Apps/Locations/Sources/Screens/LocationsList/LocationsListViewModel.swift +++ b/Apps/Locations/Sources/Screens/LocationsList/LocationsListViewModel.swift @@ -6,10 +6,17 @@ // Copyright © 2023 Röck+Cöde. All rights reserved. // +import CoreData import Combine -import Core +import Dependency +import Foundation +import Persistence class LocationsListViewModel: ObservableObject { + + // MARK: Dependencies + + @Dependency(\.persistence) private var persistence // MARK: Properties @@ -17,6 +24,15 @@ class LocationsListViewModel: ObservableObject { @Published private var viewStatus: LocationsListViewStatus = .initialised + private lazy var fetchedResultsController = NSFetchedResultsController( + fetchRequest: NSFetchRequest.allLocations(), + managedObjectContext: persistence.container.viewContext, + sectionNameKeyPath: nil, + cacheName: nil + ) + + private let loadRemoteLocations = LoadRemoteLocationsUseCase() + // MARK: Initialisers init(coordinator: LocationsListCoordination) { @@ -39,6 +55,22 @@ extension LocationsListViewModel: LocationsListViewModeling { coordinator?.openAddLocation() } + func loadLocations() { + Task { + do { + viewStatus = .loading + + try await loadRemoteLocations() + + try fetchedResultsController.performFetch() + + viewStatus = .loaded + } catch { + viewStatus = .error + } + } + } + } // MARK: - Enumerations