I have zipped two publishers in the function, which downloads users and vehicles with a backend API:
func fetchUserAndvehicles() {
Publishers.Zip(UserApiClient().getUser(), VehicleApiClient().getVehicles())
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { [weak self] completion in
switch completion {
case .failure(let error):
self?.errorHandling.showErrorAlert(error)
case .finished:
break
}
}, receiveValue: { [weak self] user, vehicles in
// store vehicles in the user object
})
.store(in: &subscriptions)
}
Each of the vehicles have an imageUrl
that can be used to download an image of the vehicle. This works fine. But I would like to download the images, if any, before I store the vehicles in the user object. Is it possible to use the same combine pipeline to do this? I tried with a flatMap
, but that resulted in a compile error.
The following is following the excellent answer from Cristik. It looks ok, but Xcode flags the flatMap
line with No exact matches in call to instance method 'flatMap'
:
let vehiclesPublisher = VehicleApiClient().getVehicles()
.flatMap { vehicles in
Publishers.Zip(Just(vehicles).setFailureType(to: Error.self), Publishers.MergeMany(vehicles.map { VehicleApiClient().getImage(at: $0.url)}).collect())
}
.map {
return $0.0
}
The vehicles have an optional property that needs to be unwrapped, but that isn't the cause of the compile error.