美文网首页
使用Action写一个网络请求

使用Action写一个网络请求

作者: CN_HarrySun | 来源:发表于2018-08-10 14:15 被阅读19次
1.在viewModel中写一个请求数据的Action
lazy var shareAction = Action<Void, (URL?, String, String)> {        //  Action<input,output> {  }
        guard let orderno = self.endModel?.orderno, let location = LocationService.shared.lastLocation else {
            return Observable.empty()
        }
        
        return ShareRequest(orderid: orderno, location: location)
            .rx
            .start(usingCache:  true)
            .mapModel(ShareModel.self)
            .catchErrorJustReturn(self.defaultShareModel)        //  请求接口失败后取默认的model
            .map {          //  map:遍历并做相应处理
                (URL(string: $0.shareUrl), $0.comment, "  " + $0.hashtag + "  ")
        }
    }
2. 在viewController中调用一次action.execute()
viewModel.shareAction.execute(())
3. action中的请求成功,返回数据之后的操作
viewModel.shareAction.elements
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [weak self] tuple in
                guard let `self` = self else { return }
                
                // 处理请求完成后的操作
            })
            .disposed(by: disposeBag)
4. 请求中的操作

请求开始时显示HUD,请求结束后隐藏HUD
distinctUntilChanged:值修改的时候才会走此方法

viewModel.shareAction.executing
            .distinctUntilChanged()          // 数据发生改变才会走
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [weak self] executing in
                if executing {
                    ProgressHUD.showLoadingHUD(in: self?.view)
                } else {
                    ProgressHUD.hideLoadingHUD(in: self?.view)
                }
            })
            .disposed(by: disposeBag)

相关文章

网友评论

      本文标题:使用Action写一个网络请求

      本文链接:https://www.haomeiwen.com/subject/imlfkftx.html