我正在使用Rx
Swift来获取一些网络数据,而我在执行每次迭代数组的请求时遇到了麻烦.这是我的想法:
>我有一个API端点,它返回一个不包含位置数据的Objs数组.然后我将循环遍历Objs数组,并为每个获取Obj id的位置详细信息.像这样的东西:
(代码简化)
var arrayObj = networkClient.request(getObjsEndpoint) .fetchObjLocationDetails(withNetworkClient: networkClient)
>而fetchObjLocationDetails()将类似于:
(代码简化)
extension ObservableType where E == [Obj]? { func fetchObjsLocationDetails(withNetworkClient networkClient: NetworkClient) -> Observable<[Obj]?> { return flatMap { Objs -> Observable<[Obj]?> in guard let unwrappedObjs = Objs as [Obj]? else { return Observable.just(nil) } let disposeBag = DisposeBag() var populatedObjs = [Obj]() unwrappedObjs.forEach { obj in let getLocationDetailsEndpoint = WeDriveParkAPI.getLocation(id: String(obj.id)) networkClient.request(getLocationDetailsEndpoint) .observeOn(MainScheduler.instance) .subscribe(onNext: { json in guard let populatedObj = Obj.fromJSON(json) as Obj? else { return } populatedObjs += [populatedObj] },onError:{ e in }).addDisposableTo(disposeBag) } return Observable.just(populatedObjs) } } }
这个解决方案并没有真正起作用,因为代码甚至没有进入订阅下一个闭包.
请记住,我是Swift和RxSwift编程的新手,所以要温柔:)任何帮助将不胜感激.
而不是制作自定义运算符,您可以使用内置.
networkClient.request(getObjsEndpoint) .map({ (objs:[Obj]?) -> [Obj] in if let objs = objs { return objs } else { throw NSError(domain: "Objs is nil",code: 1,userInfo: nil) } }) .flatMap({ (objs:[Obj]) -> Observable<[Obj]> in return objs.toObservable().flatMap({ (obj:Obj) -> Observable<Obj> in let getLocationDetailsEndpoint = WeDriveParkAPI.getLocation(id: String(obj.id)) return self.networkClient.request(getLocationDetailsEndpoint) .map({ (obj:Obj?) -> Obj in if let obj = obj { return obj } else { throw NSError(domain: "Obj is nil",userInfo: nil) } }) }).toArray() }) .subscribeNext({ (objs:[Obj]) in print("Populated objects:") print(objs) }).addDisposableTo(bag)