Handling Multiple Network Requests with Combine in Swift 5.7 and Managing Responses Efficiently
I'm currently trying to implement a feature in my iOS app where I need to fetch data from multiple network endpoints simultaneously using Combine in Swift 5.7. The goal is to process the responses and update the UI accordingly, but I'm running into some issues managing the responses effectively. I've set up my network calls using `URLSession` and `URLRequest`, but when I try to combine the results from these requests, I'm experiencing inconsistent behavior. Sometimes, I get a valid response, but other times I'm working with a situation where one of the requests fails and the entire chain is cancelled. The behavior I receive is: `CombineError.failed` without any further context. Here is the code I have so far: ```swift import Combine class NetworkManager { private var cancellables = Set<AnyCancellable>() func fetchMultipleData() { let firstPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "https://api.example.com/endpoint1")!) .map { $0.data } .decode(type: FirstResponse.self, decoder: JSONDecoder()) .eraseToAnyPublisher() let secondPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "https://api.example.com/endpoint2")!) .map { $0.data } .decode(type: SecondResponse.self, decoder: JSONDecoder()) .eraseToAnyPublisher() Publishers.Zip(firstPublisher, secondPublisher) .sink(receiveCompletion: { completion in switch completion { case .finished: print("Finished fetching data") case .failure(let behavior): print("behavior fetching data: \(behavior)") } }, receiveValue: { firstResponse, secondResponse in // Handle the responses here print(firstResponse) print(secondResponse) }) .store(in: &cancellables) } } ``` I also noticed that if the first request fails, the second request doesn’t even get executed, which isn’t the behavior I want. I would like to handle each request independently and collect their results, even if one or both unexpected result. I’ve tried using `catch` on individual publishers, but I’m unsure how to integrate that properly with `Publishers.Zip`. Could someone guide to understand how to manage the responses better in this scenario? What’s the best approach to ensure that I can still gather results from both requests regardless of their success or failure?