A
A
Andrey Myvrenik2017-09-12 12:17:36
iOS
Andrey Myvrenik, 2017-09-12 12:17:36

How to bind Alamofire+ObjectMapper+RxSwift similar to Retrofit+Gson+RxJava in Android?

Good afternoon, I recently started studying development for iOS, before that I had experience with Android. Android has such wonderful tools as:
* Retrofit + RxJava adapter - Working with HTTP
* Gson - Mapping JSON to Java objects
* RxJava - reactive language extensions
All this in one bundle allows you to create an interface ("protocol" in terms of Swift) like this:

interface MyService {
  @GET("/user")
  Observable<User> getUser();
}

And further in the code, only a method is used that returns an Observable for a result that can be subscribed to. The request itself ( GET http://mydomain.com/user), mapping and creating an Observable takes place under the hood and these things do not interfere with further development.
I want to organize something similar in Swift. Searching the Internet for available libraries, I found the following popular solutions:
* Alamofire as an analogue of Retrofit
* ObjectMapper for mapping JSON into an object
* RxSwift , RxAlamofire - reactive extensions for Swift and a wrapper for Alamofire
However, there are difficulties in understanding how to connect all this. The goal is to create one service class:
class MyService {
    func getUser() -> Observable<User> {
        // Запускаем асинхронный HTTP-запрос, маппим и возвращаем Observable. Как?
    }
}

Those. in fact, you need to make sure that the following happens in the getUser () method :
1. Alamofire makes a request
2. The response (for example ) is passed to the model for mapping:{"id":1,"name":"Jack"}
struct User: ImmutableMappable {
    let id: Int
    let name: String

    /// Маппим
    init(map: Map) throws {
        id = try map.value("id")
        name = try map.value("name")
    }
}

3. Mapping result (or error) is passed to Observer.
Perhaps someone did something like this or saw it somewhere and can share snippets? Or maybe I missed some ready-made library, which, like Retrofit, can take on the whole boring boilerplate?
UPD:
So far I've done this:
class MyService {
    func getUser() -> Observable<User> {
        return RxAlamofire.json(
                .get,
                "http://mydomain.com/user"
        ).map { json -> User in
            return try Mapper<User>().map(JSONObject: json)
        }
    }
}

WET-boilerplate saddens a little, in each method it is the same to write. But oh well, if anyone has a cleaner option - write.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Firsov, 2018-08-13
@FirsofMaxim

Thanks for the code, maybe you optimized it in a year, can you tell?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question