Unexpected Memory Leak When Using Combine with SwiftUI in iOS 16
I'm migrating some code and I'm working on a project and hit a roadblock. I'm encountering a memory leak in my SwiftUI app that uses Combine for data handling. The issue arises when I subscribe to a publisher that fetches data from a remote API. I noticed that even after the view disappears, memory for the publisher remains allocated, leading to a significant increase in memory usage. Here's a simplified version of my code: ```swift import SwiftUI import Combine class DataFetcher: ObservableObject { @Published var data: [String] = [] private var cancellables = Set<AnyCancellable>() func fetchData() { URLSession.shared.dataTaskPublisher(for: URL(string: "https://api.example.com/data")!) .map { $0.data } .decode(type: [String].self, decoder: JSONDecoder()) .receive(on: DispatchQueue.main) .assign(to: \.$data, on: self) .store(in: &cancellables) } } struct ContentView: View { @StateObject private var dataFetcher = DataFetcher() var body: some View { List(dataFetcher.data, id: \.self) { item in Text(item) } .onAppear { dataFetcher.fetchData() } } } ``` I suspect that the memory is not being released because the Combine `cancellables` set retains references to the publishers even after the view is no longer in use. Iβve tried using `onDisappear` to clear the `cancellables` set, but it doesnβt seem to have any effect on the memory usage. The memory profiling tools show that the closures within the publishers are still being held in memory, and I get the error message `Warning: Attempt to present <...> on <...> while a presentation is in progress` when navigating back to the previous view. I'm using Xcode 14 and testing on iOS 16 devices. Has anyone else faced this issue or can provide insights on proper memory management when using Combine with SwiftUI? Are there best practices in this context to ensure that subscriptions are released appropriately? Any help would be greatly appreciated! Thanks for taking the time to read this! Any help would be greatly appreciated!