Michael Michael - 1 month ago 78
Swift Question

Swift 3, RxAlamofire and mapping to custom object

I created simple project to check libraries like RxAlamofire and AlamofireObjectMapper. I have simple

ApiService
with one endpoint where is
PHP
script which works properly and returns
JSON
. I want call to
recipeURL
and I use
flatMap
operator to get response and provide it into
Mapper
where I should get
Recipe
object. How I can to do that?

Or is there other way?

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

Answer

From RxAlamofire's readme, it seems a method json(_:_:) exists in the library.

Typically, you'd rather use map instead of flatMap to transform the returned data to another format. flatMap would be useful if you needed to subscribe to a new observable (for example, doing a second request using part of the result from the first one).

 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
   }