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

时间:2016-10-30 22:01:22

标签: swift swift3 alamofire rx-swift

我创建了一个简单的项目来检查像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)
        })
    }
}

1 个答案:

答案 0 :(得分:4)

RxAlamofire的自述文件来看,图书馆中似乎存在方法json(_:_:)

通常,您宁愿使用map而不是flatMap将返回的数据转换为其他格式。如果您需要订阅新的observable(例如,使用第一个请求的部分结果执行第二个请求),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
   }