数组每次迭代的 RxSwift 请求

RxSwift request for each iteration of array

我正在使用 RxSwift 来获取一些网络数据,但我在为数组的每次迭代执行请求时遇到了问题。这是我的想法:

(代码简化)

var arrayObj = networkClient.request(getObjsEndpoint)
        .fetchObjLocationDetails(withNetworkClient: networkClient)

(代码简化)

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)
        }
    }
}

这个解决方案并没有真正起作用,因为代码甚至没有进入 subscribe next 闭包。

请记住,我是 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", code: 1, userInfo: nil)
            }
        })
    }).toArray()
})
.subscribeNext({ (objs:[Obj]) in
    print("Populated objects:")
    print(objs)
}).addDisposableTo(bag)