How do I handle networking responses with Combine with Combine in Swift?

Handling networking responses using Combine in Swift allows for a more reactive approach to managing asynchronous operations. Combine provides a powerful way to work with publishers and subscribers, making it easier to handle responses, errors, and cancellation.

Swift, Combine, Networking, Asynchronous, Publishers, Subscribers, Error Handling
Learn how to effectively utilize Combine to handle network requests and responses in Swift with clean and manageable code.

        import Combine
        import Foundation

        // Define a struct to model your data
        struct MyData: Codable {
            let id: Int
            let name: String
        }

        // Function to perform a network request
        func fetchData() -> AnyPublisher {
            let url = URL(string: "https://api.example.com/data")!
            return URLSession.shared.dataTaskPublisher(for: url)
                .map { $0.data }
                .decode(type: MyData.self, decoder: JSONDecoder())
                .receive(on: DispatchQueue.main)
                .eraseToAnyPublisher()
        }

        // Example usage
        var cancellables = Set()
        fetchData()
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    print("Request finished.")
                case .failure(let error):
                    print("Error occurred: \(error)")
                }
            }, receiveValue: { data in
                print("Received data: \(data)")
            })
            .store(in: &cancellables)
    

Swift Combine Networking Asynchronous Publishers Subscribers Error Handling