我有这个自定义的实现Alamofire
:
protocol HTTPProtocol: class { typealias RequestType typealias RespondType func doRequest(requestData: RequestType) -> Self func completionHandler(block:(Result) -> Void) -> Self } //example of a request: locationInfo //Make a request .doRequest(HTTPLocationInfo.RequestType(coordinate: $0)) //Call back when request finished .completionHandler { result in switch result { case .Success(let info): self.locationInfoRequestSuccess(info) case .Failure(let error): self.locationInfoRequestFailed(error) } }
我想将MVVM和RxSwift应用到我的项目中.但是,我找不到合适的方法来做到这一点.
我想要实现的是a ViewModel
和a ViewController
可以做这些事情:
class ViewController { func googleMapDelegate(mapMoveToCoordinate: CLLocationCoordinate2D) { // Step 1: set new value on `viewModel.newCoordinate` and make a request } func handleViewModelCallBack(resultParam: ...*something*) { // Step 3: subscribeOn `viewModel.locationInfoResult` and do things. } } class ViewModel { //Result if a wrapper object of Alamofire. typealias LocationInfoResult = (Result) -> Void let newCoordinate = Variable (kInvalidCoordinate) let locationInfoResult: Observable init() { // Step 2: on newCoordinate change, from step 1, request Location Info // I could not find a solution at this step // how to make a `completionHandler` set its result on `locationInfoResult` } }
非常感谢任何帮助.谢谢.
您可以按@Gus在评论中所述使用RxAlamofire。但是,如果您使用的是默认情况下不支持Rx扩展的任何库,则可能需要手动进行转换。
因此,对于上述代码段,您可以从已实现的回调处理程序中创建一个可观察的对象
func getResultsObservable() -> Observable{ return Observable.create{ (observer) -> Disposable in locationInfo //Make a request .doRequest( .... ) //Call back when request finished .completionHandler { result in switch result { case .Success(let info): observer.on(Event.Next(info)) case .Failure(let error): observer.on(Event.Error(NetworkError())) } } return Disposables.create { // You can do some cleaning here } } }
回调处理程序是观察者模式的实现,因此将其映射到自定义Observable是一种直接的操作。
一个好的做法是在处理的情况下取消网络请求,例如,这是一个完整的一次性Post请求:
return Observable.create { (observer) -> Disposable in let requestReference = Alamofire.request("request url", method: .post, parameters: ["par1" : val1, "par2" : val2]) .validate() .responseJSON { (response) in switch response.result{ case .success: observer.onNext(response.map{...}) observer.onCompleted() case .failure: observer.onError(NetworkError(message: response.error!.localizedDescription)) } } return Disposables.create(with: { requestReference.cancel() })
注意:将swift 3 Disposables.create()
替换为NopDisposable.instance