I use RxSwift to get some network data, and I am having trouble running a query for each iteration of the array. That was my idea:
- I have an API endpoint that returns an Objs array that does not contain location data. Then I would go through the Objs array and for each I get the location details with the Obj identifier. Something like that:
(simplified code)
var arrayObj = networkClient.request(getObjsEndpoint)
.fetchObjLocationDetails(withNetworkClient: networkClient)
- And fetchObjLocationDetails () will look something like this:
(simplified code)
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)
}
}
}
This solution really does not work, because the code is not even included in the next subscription.
Please remember that I am new to Swift and RxSwift programming, so be careful :) Any help would be greatly appreciated.