SwiftUI: How to prevent duplicated API calls when using EnvironmentObject across multiple views?
I'm relatively new to this, so bear with me. I'm trying to debug I'm experimenting with I've searched everywhere and can't find a clear answer. I've been struggling with this for a few days now and could really use some help. I'm currently working on a SwiftUI application where I have an `ObservableObject` that manages user data fetched from an API. I pass this `ObservableObject` using `@EnvironmentObject` to multiple views. However, I'm encountering a problem where the data fetching method gets called multiple times whenever I navigate between these views. I'm using Swift 5.7 and iOS 17. Here's a simplified version of my code: ```swift class UserData: ObservableObject { @Published var users: [User] = [] var cancellable: AnyCancellable? func fetchUsers() { guard users.isEmpty else { return } // Prevent multiple fetches cancellable = URLSession.shared.dataTaskPublisher(for: URL(string: "https://api.example.com/users")!) .map { $0.data } .decode(type: [User].self, decoder: JSONDecoder()) .replaceError(with: []) .receive(on: DispatchQueue.main) .assign(to: &$users) } } struct ContentView: View { @EnvironmentObject var userData: UserData var body: some View { NavigationView { VStack { List(userData.users) { user in Text(user.name) } .onAppear { userData.fetchUsers() } // This seems to trigger multiple fetches NavigationLink(destination: DetailView()) { Text("Go to Detail") } } } } } struct DetailView: View { @EnvironmentObject var userData: UserData var body: some View { Text("Detail View") .onAppear { userData.fetchUsers() } // This duplicates fetch on navigation } } ``` I tried adding a guard statement in `fetchUsers()` to prevent duplicate API calls, but it doesn't seem to work correctly when switching between views. The `users` array is still being fetched again when I navigate back to `ContentView`. The expected behavior is that data should only be fetched once and reused. Is there a better way to structure this so that the API call occurs only once when the app starts or when the data is actually needed? Any suggestions or best practices for managing API calls in a SwiftUI environment would be greatly appreciated. For context: I'm using Swift on Linux. My development environment is Linux. Am I missing something obvious? I'm working with Swift in a Docker container on CentOS. How would you solve this? I recently upgraded to Swift stable. I'm working with Swift in a Docker container on Ubuntu 20.04. What's the correct way to implement this?