i70ro
i70ro

Reputation: 111

Set request timeout on RXMoyaProvider

I am using Moya with RxSwift and I am trying to set the request timeout for the network call (API Calls) using below code as suggested :

which is including the custom Alamofire Manager when declaring your Provider

lazy var provider: RxMoyaProvider<CAPProviderAPI> = {
    return RxMoyaProvider<CAPProviderAPI>(endpointClosure: Utility.getEndPointClosure(forProviderType: .authorized), manager: DefaultAlamofireManager.sharedManager, plugins: [NetworkActivityPlugin(networkActivityClosure: networkActivityClosure)])
}()

but I am getting an error saying : Use of unresolved identifier 'networkActivityClosure'

Upvotes: 0

Views: 1519

Answers (1)

iWheelBuy
iWheelBuy

Reputation: 5679

I would like to share with you the way I did it. It might not answer your question, but it shows the way to achieve the desired behavior using RxSwift operators.

I have some function which accepts timeout parameter and makes a request:

func request(timeout: TimeInterval, ...other params) -> Observable<...>

Inside this function I transform timeout to Observable this way:

func observableTimeout(timeout: TimeInterval, ...other params) -> Observable<...> {
    return Observable<Int>
        .timer(timeout, period: ..., scheduler: ...)
        .take(1)
        .map(to: ...) // map to timeout error
}

If the timeout takes place - I need to cancel the request. I have made some flatMapLatest analogue which also accepts a cancel signal:

public extension Observable {
    public func flatMapLatest<T>(cancel: Observable<T>, factory: @escaping (E) throws -> Observable<T>) -> Observable<T> {
        let observableNormal = self
            .flatMap({ try factory($0) })
        return Observable<Observable<T>>
            .of(cancel, observableNormal)
            .merge()
            .take(1)
    }
}

As a result, the request function will work this way:

func request(timeout: TimeInterval, ...other params) -> Observable<...> {
    let cancel = observableTimeout(timeout: timeout, ...)
    let factory = ...// your observable factory which makes a request using Moya
    return Observable
        .just((), scheduler: ...)
        .flatMapLatest(cancel: cancel, factory: factory)
}

Upvotes: 2

Related Questions