Removing Swift RxAlamofire dependency

155 views Asked by At

I'm trying to remove my dependency on RxAlamofire.

I currently have this function:

  func requestData(_ urlRequest: URLRequestConvertible) -> Observable<(HTTPURLResponse, Data)> {

    RxAlamofire.request(urlRequest).responseData()

  }

How can I refactor this and use Alamofire directly to build and return an RxSwift Observable?

1

There are 1 answers

0
Daniel T. On

I suggest you look at the way the library wraps URLRequest to get an idea on how to do it...

Below is an abbreviated example from the library. In essence, you need to use Observable.create, make the network call passing in a closure that knows how to use the observer that create gives you.

Make sure you send a completed when done and make sure the disposable knows how to cancel the request.

Your Base will be something in Alamofire (I don't use Alamofire so I'm not sure what that might be.)

extension Reactive where Base: URLSession {
    /**
    Observable sequence of responses for URL request.
    
    Performing of request starts after observer is subscribed and not after invoking this method.
    
    **URL requests will be performed per subscribed observer.**
    
    Any error during fetching of the response will cause observed sequence to terminate with error.
    
    - parameter request: URL request.
    - returns: Observable sequence of URL responses.
    */
    public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
        return Observable.create { observer in
            let task = self.base.dataTask(with: request) { data, response, error in
                guard let response = response, let data = data else {
                    observer.on(.error(error ?? RxCocoaURLError.unknown))
                    return
                }

                guard let httpResponse = response as? HTTPURLResponse else {
                    observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response)))
                    return
                }

                observer.on(.next((httpResponse, data)))
                observer.on(.completed)
            }

            task.resume()

            return Disposables.create(with: task.cancel)
        }
    }
}