我正在努力结合两个请求。我需要第一个id
,然后从接收到的列表中的第一个id
开始第二个。我找不到通过Swift Combine做到这一点的好方法。
我的第一个请求看起来像CarSerview.shared.getCategories() -> AnyPublisher<[Category], CarError>
:
private func getCategories() {
CarSerview.shared.getCategories()
.receive(on: DispatchQueue.main)
.map { car in
return car.id
}
.replaceError(with: [])
.assign(to: \.carsIds, on: self)
.store(in: &cancellable)
}
第二个看起来像CarSerview.shared.getCar() -> AnyPublisher<Car, CarError>
:
private func getCar(_ category: CategoryObject) {
SPService.shared.getExcursions(category)
.receive(on: DispatchQueue.main)
.map { car in
return car.cars.compactMap { $0.name }
}
.sink(receiveCompletion: { error in
print(error)
}, receiveValue: { [weak self] result in
self?.cars = result
})
}
如何将这两个请求合而为一?
答案 0 :(得分:2)
无法测试,但想法是使用.map + .switchToLatest,因此可以如下所示
private func getCars() {
CarSerview.shared.getCategories()
.map { car in
return SPService.shared.getExcursions(car.id)
}
.switchToLatest()
.receive(on: DispatchQueue.main)
.map { car in
return car.cars.compactMap { $0.name }
}
.sink(receiveCompletion: { error in
print(error)
}, receiveValue: { [weak self] result in
self?.cars = result
})
}