How do I inject dependencies cleanly in Combine with Swift?

Dependency injection in Swift using Combine can be done in a clean and efficient manner. By using protocols and initializer injection, you can create a modular and testable architecture for your Swift applications. Below is an example of how you can implement this approach.

// Protocol for a service protocol DataService { func fetchData() -> AnyPublisher } // Implementation of the service class ApiDataService: DataService { func fetchData() -> AnyPublisher { // Replace with actual API call Just(Data()) .setFailureType(to: Error.self) .eraseToAnyPublisher() } } // ViewModel that receives the service via dependency injection class ViewModel: ObservableObject { @Published var data: Data? private var cancellables = Set() private let dataService: DataService init(dataService: DataService) { self.dataService = dataService } func loadData() { dataService.fetchData() .sink(receiveCompletion: { completion in // Handle completion }, receiveValue: { [weak self] value in self?.data = value }) .store(in: &cancellables) } } // Usage let service = ApiDataService() let viewModel = ViewModel(dataService: service) viewModel.loadData()

Swift Combine Dependency Injection SwiftUI ViewModel Modular Architecture