我需要从网络请求不同类型的模型,然后将它们组合成一个模型。 如何链接多个 observable 并返回另一个 observable?
我有这样的东西:
func fetchDevices() -> Observable<DataResponse<[DeviceModel]>>
func fetchRooms() -> Observable<DataResponse<[RoomModel]>>
func fetchSections() -> Observable<DataResponse<[SectionModel]>>
我需要做类似的事情:
func fetchAll() -> Observable<(AllModels, Error)> {
fetchSections()
// Then if sections is ok I need to fetch rooms
fetchRooms()
// Then - fetch devices
fetchDevices()
// And if everything is ok create AllModels class and return it
// Or return error if any request fails
return AllModels(sections: sections, rooms: rooms, devices:devices)
}
如何用RxSwift实现?我阅读了文档和示例,但了解如何链接具有相同类型的可观察对象
最佳答案
尝试 combineLatest
运算符。您可以组合多个可观察对象:
let data = Observable.combineLatest(fetchDevices, fetchRooms, fetchSections)
{ devices, rooms, sections in
return AllModels(sections: sections, rooms: rooms, devices:devices)
}
.distinctUntilChanged()
.shareReplay(1)
然后,您订阅它:
data.subscribe(onNext: {models in
// do something with your AllModels object
})
.disposed(by: bag)
关于ios - 链接不同类型的 RxSwift observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45471978/