Bruno Morgado
Bruno Morgado

Reputation: 507

RxSwift request for each iteration of array

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.

Upvotes: 6

Views: 5595

Answers (1)

Evgeny Sureev
Evgeny Sureev

Reputation: 1028

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)

Upvotes: 8

Related Questions