Hello,
I was browsing through book and one thing caught my attention in ContentView. You are initialising AnimalsNearYouViewModel inside View body there which is ObservableObject and holds some state in @Published properties.
So each time location changes and ContentView’s body gets called you will make new instance of AnimalsNearYouViewModel and reset it’s state.
Am I missing something here? If not I think this is not desired behaviour. In my projects I never initialise ViewModels inside View body because in general it can cause very undesirable behaviour. Also it will make lot of heap allocations since each time new reference type is created that is also performance hit.
struct ContentView: View {
let managedObjectContext = PersistenceController.shared.container.viewContext
@StateObject var locationManager = LocationManager()
var body: some View {
TabView {
AnimalsNearYouView(
viewModel: AnimalsNearYouViewModel(
animalFetcher: FetchAnimalsService(
requestManager:
RequestManager()
),
animalStore: AnimalStoreService(
context: PersistenceController.shared.container.newBackgroundContext()
)
)
)
.tabItem {
Label("Near you", systemImage: "location")
}
.environment(\.managedObjectContext, managedObjectContext)
SearchView()
.tabItem {
Label("Search", systemImage: "magnifyingglass")
}
.environment(\.managedObjectContext, managedObjectContext)
}
.environmentObject(locationManager)
}
}