iOS-项目实战

RxSwift 对基于 AFNetworking 的网络请求组件

2020-12-28  本文已影响0人  SoaringHeart

项目中需要使用 RxSwift 的部分特性(throttle 与 debounce、 Observable.zip() ...),所以将原来的网络框架进行了部分改造,进而进行简单的二次封装,最终完美达成目标

第一步:将原本的网络封装请求类改造
原本的网络请求基类(IOPRequestManager)是返回为 void 的,改为返回 NSURLSessionDataTask 类型即可;

第二部:做简单二次封装, 如下扩展即可:

🌰 🌰 :
    ///编辑用户信息
    func requestUserUpdateInfo(_ block: ((Int)->Void)?) {
        userUpdateAPI.rx.requestAsSingle()
            .subscribe(onSuccess: { (dic) in
//            DDLog(dic)
            let message = (dic["message"] ?? kAPISuccess) as! String
            IOPProgressHUD.showText(message)
                
            guard let code = dic["code"] as? NSNumber else {
                IOPProgressHUD.showError(withStatus: "code 未返回")
                return }
                block?(code.intValue)

        }) { (error) in
            IOPProgressHUD.showError(withStatus: (error as NSError).domain)
        }
        .disposed(by: disposeBag)
    }


    ///获取用户信息,钱包信息
    func requestUserInfo(_ block: (()->Void)?, failblock: ((Error)->Void)?) {
        Observable.zip( userInfoAPI.rx.request(),
                        userWalletinfoAPI.rx.request())
            .asSingle()
            .subscribe(onSuccess: { (dic, dic1) in
    //            DDLog(dic)
                if let userModel = PKUserInfoDetailModel.yy_model(with: dic) {
                    IOPStorageManager.userModel = userModel
                    IOPStorageManager.phone = userModel.phone
                    let tmpModel = IOPStorageManager.userModel
                    DDLog(tmpModel)
                }

                if let walletModel = PKUserWalletDetaiIModel.yy_model(with: dic) {
                    IOPStorageManager.walletModel = walletModel
                    DDLog(walletModel)
                }
                                
                block?()
            }) { (error) in
//                IOPProgressHUD.showError(withStatus: (error as NSError).domain)
                failblock?(error)
                
            }.disposed(by: disposeBag)
                
    }

对基类进行二次封装:


//解析相关错误
public enum RxMapModelError: Error {
    case parsingError
}

extension Reactive where Base: IOPRequestManager {
    
    func requestAsSingle() -> Single<[AnyHashable: Any]> {
        return request().asSingle()
    }

    func request() -> Observable<[AnyHashable: Any]> {
        return Observable.create{ observer in
            let task = self.base.startRequest(successBlock: { (manager, dic) in
                observer.onNext(dic)
                observer.onCompleted()
            }) { (manager, errorModel) in
                let error = NSError(domain: errorModel.message ?? "出现未知错误", code: errorModel.code, userInfo: nil)
                observer.onError(error)
            }
            
            return Disposables.create {
                if let task = task {
                    task.cancel()
                }
            }
        }
    }
}

YYModel 的 RxSwift 封装

//.扩展Observable:增加模型映射方法
public extension Observable where Element: Any {
    
    //YYModel 将JSON数据转成对象
    func mapYYModel<T: NSObject>(type: T.Type) -> Observable<T> {
        return self.map { (element) -> T in
            guard let parsedElement = T.yy_model(withJSON: element) else {
                throw RxMapModelError.parsingError
            }
            return parsedElement
        }
    }
    
    // YYModel 将JSON数据转成数组
    func mapYYModels<T: NSObject>(type: T.Type) -> Observable<[T]> {
        return self.map { (element) -> [T] in
            guard let parsedArray = NSArray.yy_modelArray(with: T.self, json: element) as? [T] else {
                throw RxMapModelError.parsingError
            }
            return parsedArray
        }
    }
}

HandyJSON 的 RxSwift 封装

//.扩展Observable:增加模型映射方法
public extension Observable where Element: Any {
    
    //HandyJSON 将JSON数据转成对象
    func mapHandyJSONModel<T: HandyJSON>(type: T.Type) -> Observable<T> {
        return self.map { (element) -> T in
            guard let parsedElement = T.deserialize(from: element as? Dictionary) else {
                throw RxMapModelError.parsingError
            }
            return parsedElement
        }
    }
    
    //HandyJSON 将JSON数据转成数组
    func mapHandyJSONModels<T: HandyJSON>(type: T.Type) -> Observable<[T]> {
        return self.map { (element) -> [T] in
            guard let parsedArray = [T].deserialize(from: element as? [Any]) as? [T] else {
                throw RxMapModelError.parsingError
            }
            return parsedArray
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读