Memory Leak in iOS 16 with Combine and SwiftUI for Nested Views
I'm trying to figure out I'm not sure how to approach I'm trying to debug I'm trying to configure I'm experiencing a memory leak scenario in my iOS 16 app that uses Combine with SwiftUI for handling nested views..... The app is structured to fetch data from a REST API and populate a detailed view when a user taps on an item in a list. The question arises when navigating back from the detailed view to the list; the view memory is not being released, causing a noticeable increase in memory usage. I've tried using the `onDisappear` modifier in SwiftUI to cancel any active subscriptions, but it doesn't seem to prevent the leak. Here's a code snippet showing how I'm setting up the Combine publisher in my `DetailView`: ```swift class DetailViewModel: ObservableObject { @Published var item: Item? private var cancellables = Set<AnyCancellable>() func fetchItemDetails(id: String) { APIService.shared.fetchItem(by: id) .receive(on: DispatchQueue.main) .assign(to: \.$item, on: self) .store(in: &cancellables) } } ``` In my `DetailView`, I call `fetchItemDetails` when the view appears: ```swift struct DetailView: View { @StateObject var viewModel = DetailViewModel() var itemId: String var body: some View { Text(viewModel.item?.name ?? "Loading...") .onAppear { viewModel.fetchItemDetails(id: itemId) } .onDisappear { // Attempting to cancel subscriptions viewModel.cancellables.removeAll() } } } ``` Despite this, when I navigate back, the memory usage continues to climb, and Instruments shows that `DetailView` instances are not being deallocated as expected. I've also checked for retain cycles, but I'm not holding any strong references that could cause this. Can anyone suggest what might be going wrong or any best practices to handle Combine publishers in SwiftUI to prevent memory leaks? I've also enabled the `Debug Memory Graph` tool but found no obvious issues. Any insights would be appreciated! Am I approaching this the right way? Any ideas what could be causing this? Cheers for any assistance! This is happening in both development and production on Linux. Has anyone else encountered this? The project is a CLI tool built with Swift.