How do I cancel subscriptions and avoid memory leaks with Combine in Swift?

In Swift, when working with Combine, managing subscriptions is crucial for avoiding memory leaks. It's essential to cancel your subscriptions appropriately, either when they are no longer needed or within the appropriate lifecycle methods of your classes. Below is an example demonstrating how to correctly handle Combine subscriptions and avoid memory leaks.

import Combine class DataFetcher { private var cancellables = Set() func fetchData() { let publisher = Just("Hello, Combine!") publisher .sink { value in print(value) } .store(in: &cancellables) // Store the subscription } deinit { // Clean up subscriptions when the class instance is deallocated cancellables.removeAll() } } let fetcher = DataFetcher() fetcher.fetchData()

Swift Combine Memory Leaks Subscriptions Cancellables