9

我有这个自定义实现Alamofire

protocol HTTPProtocol: class {
    typealias RequestType
    typealias RespondType
    func doRequest(requestData: RequestType) -> Self
    func completionHandler(block:(Result<RespondType, NSError>) -> 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 应用到我的项目中。但是,我找不到合适的方法来做到这一点。

我想要实现的是 aViewModel和 aViewController可以做这些事情:

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<LocationInfo.Respond, NSError>) -> Void
    let newCoordinate = Variable<CLLocationCoordinate2D>(kInvalidCoordinate)
    let locationInfoResult: Observable<LocationInfoResult>

    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`
    }
}

任何帮助都深表感谢。谢谢你。

4

2 回答 2

7

您可以按照@Gus 在评论中所说的那样使用RxAlamofire。但是,如果您使用的是默认情况下不支持 Rx 扩展的任何库,您可能需要手动进行转换。

所以对于上面的代码片段,你可以从你已经实现的回调处理程序中创建一个 observable

    func getResultsObservable() -> Observable<Result> {
        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<Result>.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

于 2016-07-28T15:05:38.240 回答
0

您似乎不需要订阅,newCoordinate所以我会提出请求func

然后,使用您从 Alamofire 返回的信息,只需在 上设置值locationInfoResult,您将在ViewController

class ViewController: UIViewController {
    func viewDidLoad() {
        super.viewDidLoad()

        //subscribe to info changes
        viewModel.locationInfoResult
            .subscribeNext { info in 
                //do something with info...
            }
    }

    func googleMapDelegate(mapMoveToCoordinate: CLLocationCoordinate2D) {
        viewModel.requestLocationInfo(mapMoveToCoordinate)
    }
}

class ViewModel {
    let locationInfoResult: Variable<LocationInfoResult?>(nil)

    init() {
    }

    func requestLocationInfo(location: CLLocationCoordinate2D) {
        //do Alamofire stuff to get info

        //update with the result
        locationInfoResult.value = //value from Alamofire
    }
}
于 2015-12-29T17:07:00.010 回答