Swift 3,RxAlamofire并映射到自定义对象

Mic*_*ael 0 swift alamofire rx-swift swift3

我创建了一个简单的项目来检查RxAlamofire和AlamofireObjectMapper之类的库。我有ApiService一个端点很简单,PHP脚本可以正常工作并返回JSON。我想打电话给recipeURL我,我用flatMap运算符来获取响应,并将其提供Mapper给应该获取Recipe对象的位置。我该怎么做?

还是有其他方法?

class ApiService:  ApiDelegate{
    let recipeURL = "http://example.com/test/info.php"

    func getRecipeDetails() -> Observable<Recipe> {
        return request(.get, recipeURL)
            .subscribeOn(MainScheduler.asyncInstance)
            .observeOn(MainScheduler.instance)
            .flatMap({ request -> Observable<Recipe> in
                let json = ""//request.??????????? How to get JSON response?
                guard let recipe: Recipe = Mapper<Recipe>().map(JSONObject: json) else {
                    return Observable.error(ApiError(message: "ObjectMapper can't mapping", code: 422))
                }
            return Observable.just(recipe)
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

tom*_*ahh 5

RxAlamofire的自述文件来看json(_:_:),库中似乎存在一种方法。

通常,您宁愿使用map而不是flatMap将返回的数据转换为另一种格式。flatMap如果您需要订阅新的可观察对象(例如,使用第一个结果的一部分进行第二个请求),则将很有用。

 return json(.get, recipeURL)
   .map { json -> Recipe in
     guard let recipe = Mapper<Recipe>().map(JSONObject: json) else {
       throw ApiError(message: "ObjectMapper can't mapping", code: 422)
     }
     return recipe
   }
Run Code Online (Sandbox Code Playgroud)