gpt4 book ai didi

ios - 链接不同类型的 RxSwift observable

转载 作者:搜寻专家 更新时间:2023-11-01 06:02:29 27 4
gpt4 key购买 nike

我需要从网络请求不同类型的模型,然后将它们组合成一个模型。如何链接多个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com