【问题标题】:Swift 3, RxAlamofire and mapping to custom objectSwift 3、RxAlamofire 和映射到自定义对象
【发布时间】:2016-10-30 22:01:22
【问题描述】:

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

【问题讨论】:

    标签: swift swift3 alamofire rx-swift


    【解决方案1】:

    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
       }
    

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2013-02-27
      • 2021-11-07
      • 2021-05-02
      • 2017-10-02
      • 2018-10-31
      相关资源
      最近更新 更多