RxSwift request for each iteration of the array

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.

+4
1

.

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)
+5

Source: https://habr.com/ru/post/1628478/


All Articles