Michael Michael - 1 year ago 469
Swift Question

Swift 3, RxAlamofire and mapping to custom object

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

with one endpoint where is
script which works properly and returns
. I want call to
and I use
operator to get response and provide it into
where I should get
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)
.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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download