该RxSwift实战主要是将网络音乐评论通过表格的形式显示出来,主要展示的内容有用户头像、昵称、评论内容。YFNetwork是对Moya的进一步封装,更加方便使用,请求得到的数据通过PublishSubject发送到已绑定的UITableView。
final class YFCommentVM{
private let disposeBag = DisposeBag()
var data = PublishSubject<[YFCommentItemModel]>()
var commentArray = [YFCommentItemModel]()
var isNoMore = false
private var curPage:Int = 1
private let pagesize:Int = 20
func reloadData(completed:@escaping (_ isNoMore:Bool)->()){
curPage = 1
loadData(offset: (curPage - 1) * pagesize,completed: completed)
}
func loadMoreData( completed:@escaping (_ isNoMore:Bool)->()){
curPage += 1
loadData(offset: (curPage - 1) * pagesize,completed: completed)
}
func loadData(offset:Int, completed:@escaping (_ isNoMore:Bool)->()) {
YFNetwork.request(target: YFAPI.comment(limit: pagesize, offset: offset)).subscribe {response in
do {
let commentModel = try JSONDecoder().decode(YFCommentModel.self, from: response as! Data)
if self.curPage <= 1 {
self.commentArray.removeAll()
}
if let comments = commentModel.comments{
self.commentArray.append(contentsOf: comments)
}
if let total = commentModel.total{
self.isNoMore = self.curPage * self.pagesize >= total
}
self.data.onNext(self.commentArray)
} catch {
debugPrint("error == \(error)")
}
completed(self.isNoMore)
} onFailure: { error in
debugPrint("error == \(error)")
completed(self.isNoMore)
}.disposed(by: disposeBag)
}
}
UITableView监听到数据,刷新并把数据显示出来。
func initUI(){
commentTableView.rowHeight = 64.0
commentTableView.separatorStyle = .none
commentTableView.register(UINib.init(nibName: cellReuseIdentifier, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
commentVM.data.bind(to: commentTableView.rx.items(cellIdentifier: cellReuseIdentifier , cellType: YFCommentCell.self)){(index, model, cell) in
cell.setData(model: model)
}.disposed(by: disposeBag)
}
UITableView点击cell查看评论详情。
commentTableView.rx.modelSelected(YFCommentItemModel.self).subscribe { [weak self] itemModel in
let cdVC = YFCommentDetailVC()
cdVC.model = itemModel.element
self?.navigationController?.pushViewController(cdVC, animated: true)
}.disposed(by: disposeBag)
UITableView上拉刷新,下拉加载更多。
commentTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
self?.commentVM.reloadData(completed:{ isNoMore in
if isNoMore {
self?.commentTableView.mj_footer?.endRefreshingWithNoMoreData()
} else {
self?.commentTableView.mj_header?.endRefreshing()
}
})
})
commentTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
self?.commentVM.loadMoreData(completed:{ isNoMore in
if isNoMore {
self?.commentTableView.mj_footer?.endRefreshingWithNoMoreData()
} else {
self?.commentTableView.mj_footer?.endRefreshing()
}
})
})