Swift 5.7: Difficulty with Combine and URLSession in handling multiple API requests concurrently
I'm experimenting with I'm trying to figure out I've been banging my head against this for hours... I'm working with Swift 5.7 and working with an scenario when using Combine with URLSession to handle multiple API requests concurrently. I'm trying to fetch data from two different endpoints and combine the results into a single model. However, when I run the code, the second request seems to be ignored, and I only get the result from the first request. Hereβs a simplified version of what I have: ```swift import Foundation import Combine struct ApiResponse: Decodable { let id: Int let name: String } class ApiService { private var cancellables = Set<AnyCancellable>() func fetchAllData() { let url1 = URL(string: "https://api.example.com/data1")! let url2 = URL(string: "https://api.example.com/data2")! let request1 = URLSession.shared.dataTaskPublisher(for: url1) .map { $0.data } .decode(type: ApiResponse.self, decoder: JSONDecoder()) .catch { _ in Just(nil) } .share() let request2 = URLSession.shared.dataTaskPublisher(for: url2) .map { $0.data } .decode(type: ApiResponse.self, decoder: JSONDecoder()) .catch { _ in Just(nil) } .share() request1 .combineLatest(request2) .sink(receiveCompletion: { completion in switch completion { case .finished: break case .failure(let behavior): print("behavior: \(behavior)") } }, receiveValue: { response1, response2 in print("Response 1: \(response1)") print("Response 2: \(response2)") }) .store(in: &cancellables) } } ``` When I execute `fetchAllData()`, I only get the output from `Response 1`, and `Response 2` is always `nil`. I've checked the URLs and they both return valid responses when accessed directly in a browser. I've also tried removing the `.share()` operator thinking it might be causing the scenario, but it didn't resolve anything. Any ideas on what could be going wrong with my Combine pipeline or if there are best practices for handling multiple API calls concurrently in Swift? Thanks in advance! This is my first time working with Swift latest. My development environment is Windows 11. Hoping someone can shed some light on this. I'd really appreciate any guidance on this.