cojoj
cojoj

Reputation: 6475

Alamofire retry request - reactive way

I was looking at those two:

And trying to create similiar thing, but without Moya, using Alamofire + RxSwift.

First of all is obviously where should I stick this, since my implementation is divided into a couple smaller parts. First of all I have my custom method for generating reactive requests:

static func rx_request<T>(requestConvertible: URLRequestConvertible, completion: (Request) -> Observable<T> ) -> Observable<T> {
    let manager: Manager = Manager.sharedInstance
    return manager
        .rx_request { manager -> Request in
            return Alamofire.request(requestConvertible)
        }
        .flatMap { request -> Observable<T> in
            return completion(request)
        }
        .shareReplay(1)
}

Which is later used by specific Requests convenience classes. For example my UserRequests has this private extension to extract some common code from it's methods:

private extension Request {

    func rx_userRequest() -> Observable<User> {
        return self
            .validate()
            .rx_responseJSON()
            .flatMap{ (request, json) -> Observable<User> in
                guard
                    let dict = json as? [ String: AnyObject ],
                    let parsedUser: User = try? Unbox(dict) else {
                        return Observable.error(RequestError.ParsingError)
                }

                return Observable.just(parsedUser)
            }
            .rx_storeCredentials()
    }

}

Because of how things looks like I wonder whare's the right place to put a retry method and also how to implement it? Because depending on the location I can get different input arguments.

Upvotes: 2

Views: 1155

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The retry code has to go after the first try, which is rx_responseJSON so the way you have things setup now, it must go between that and the flatMap after it.

Upvotes: 1

Related Questions