swiftuicore-data

Trigger ViewModel update deep inside navigation stack


I have a view model with a published array foodItems, containing the data for a List in the related parent View. The array is initially filled from CoreData by calling the loadFoodItems function.

class FoodListViewModel: ObservableObject {
    private(set) var category: FoodItemCategory

    @Published var foodItems: [FoodItemViewModel] = []

    init() {
        self.category = category
        loadFoodItems()
    }

    func loadFoodItems() {
        foodItems = FoodItem.fetchAll(for: category).map { FoodItemViewModel(from: $0) }
    }
}

The related parent View has a number of child views and grandchild views, which are called by appending to a NavigationPath. In many of these views, the CoreData underlying the foodItem variable can be modified. When returning to the parent, the view is not updated, as only the CoreData are modified and the loadFoodItems function has not been called since.

Is there a better way to trigger an update of the parent view than passing the view model along to all child and grandchild views and to call the loadFoodItems function from there?


Solution

  • Simply remove the unnecessary view model class, use the SwiftUI View struct and @FetchRequest with a predicate for the category. body will be called whenever objects in the context that match the predicate change.