RxAlamofire post multipart data

2.6k views Asked by At

How to send Multipart data with RxAlamofire

For instance in Alamofire

let URL = try! URLRequest(url: "http://example.com", method: .post)


Alamofire.upload(multipartFormData: { formData in
    // multiaprt
}, with: URL, encodingCompletion: {(result: SessionManager.MultipartFormDataEncodingResult) in

})
  1. How to get same behaviour/function with RxAlamofire?
  2. Or An way of wrapping this function in an Observable?
1

There are 1 answers

0
xandrefreire On

You can easily wrap that function like this:

func wrapper() -> Observable<SomeResponseType> {
    return Observable.create { observer in

        let URL = try! URLRequest(url: "http://example.com", method: .post)

        Alamofire.upload(
            multipartFormData: { formData in
                // multiaprt
            }, 
            with: URL, 
            encodingCompletion: { encodingResult in

                switch encodingResult {

                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        // convert response in something of SomeResponseType
                        // ...
                    observer.onNext(response)
                    observer.onCompleted()
                }
                case .failure(let encodingError):
                    observer.onError(encodingError)
                }
            })

        return Disposables.create()
    }
}