How do I structure feature modules in Combine with Swift?

Structuring feature modules in a Swift application using Combine can help you maintain a clean and modular architecture. By dividing your application into feature modules, you can enhance code reusability, facilitate testing, and manage dependencies more efficiently.

Here’s a simple approach to organizing feature modules with Combine:

import Combine

struct User {
    let id: String
    let name: String
}

class UserService {
    func fetchUser(id: String) -> AnyPublisher {
        // Simulate a network call
        Just(User(id: id, name: "John Doe"))
            .setFailureType(to: Error.self)
            .eraseToAnyPublisher()
    }
}

class UserViewModel: ObservableObject {
    @Published var user: User?
    private var cancellables = Set()
    private let userService: UserService

    init(userService: UserService) {
        self.userService = userService
    }

    func getUser(id: String) {
        userService.fetchUser(id: id)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break
                case .failure(let error):
                    print("Error fetching user: \(error)")
                }
            }, receiveValue: { [weak self] user in
                self?.user = user
            })
            .store(in: &cancellables)
    }
}

This example demonstrates how to create a simple user module using Combine in Swift. It contains a User model, a UserService for fetching user data, and a UserViewModel that bridges the model and the view.


Swift Combine feature modules modular architecture code reusability dependency management