I'm using RxSwift to fetch some network data and I'm having trouble with performing a request for each iteration of an array. This was my idea:
(code simplified)
var arrayObj = networkClient.request(getObjsEndpoint)
.fetchObjLocationDetails(withNetworkClient: networkClient)
(code simplified)
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 is not really working because the code doesn't even go inside the subscribe next closure.
Please have in mind I'm new to both Swift and RxSwift programming so be gentle :) Any help would be greatly appreciated.
Instead of making custom operator you can use built-in.
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", code: 1, userInfo: nil)
}
})
}).toArray()
})
.subscribeNext({ (objs:[Obj]) in
print("Populated objects:")
print(objs)
}).addDisposableTo(bag)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With