RxSwift 很是强大,用得好,很爽git
场景举例,就是两表关联。 RxDataSource,怎样列表刷新出来,就自动选择第一个。而后子列表根据上一个列表的选择,确认要刷新的数据。编程
左边一个列表 tableView, 右边一个列表 tableView , 两个列表之间的数据存在关联,左边列表是一级选项,右边列表是对应左边的二级选项。bash
private var lastIndex : NSInteger = 0
// ...
// 看这一段代码,就够了
let leftDataSource = RxTableViewSectionedReloadDataSource<CategoryLeftSection>( configureCell: { [weak self] ds, tv, ip, item in
guard let strongSelf = self else { return UITableViewCell()}
let cell : CategoryLeftCell = tv.dequeueReusableCell(withIdentifier: "Cell1", for: ip) as! CategoryLeftCell
cell.model = item
// 看这一句代码,就够了
if ip.row == strongSelf.lastIndex {
// ...
tv.selectRow(at: ip, animated: false, scrollPosition: .top)
tv.delegate?.tableView!(tv, didSelectRowAt: ip)
}
return cell
})
vmOutput!.sections.asDriver().drive(self.leftMenuTableView.rx.items(dataSource: leftDataSource)).disposed(by: rx.disposeBag)
// 选择左边列表,给右边提供的数据
let rightPieceListData = self.leftMenuTableView.rx.itemSelected.distinctUntilChanged().flatMapLatest {
[weak self](indexPath) -> Observable<[SubItems]> in
guard let strongSelf = self else { return Observable.just([]) }
strongSelf.currentIndex = indexPath.row
if indexPath.row == strongSelf.viewModel.vmDatas.value.count - 1 {
// ...
strongSelf.leftMenuTableView.selectRow(at: strongSelf.currentSelectIndexPath, animated: false, scrollPosition: .top)
strongSelf.leftMenuTableView.delegate?.tableView!(strongSelf.leftMenuTableView, didSelectRowAt: strongSelf.currentSelectIndexPath!)
return Observable.just((strongSelf.currentListData)!)
}
if let subItems = strongSelf.viewModel.vmDatas.value[indexPath.row].subnav {
// ...
var reult:[SubItems] = subItems
// ...
strongSelf.currentListData = reult
strongSelf.currentSelectIndexPath = indexPath
return Observable.just(reult)
}
return Observable.just([])
}.share(replay: 1)
// 右边列表的数据源,具体 cell 的配置方法
let rightListDataSource = RxTableViewSectionedReloadDataSource<CategoryRightSection>( configureCell: { [weak self]ds, tv, ip, item in
guard let strongSelf = self else { return UITableViewCell() }
if strongSelf.lastIndex != strongSelf.currentIndex {
tv.scrollToRow(at: ip, at: .top, animated: false)
strongSelf.lastIndex = strongSelf.currentIndex
}
if ip.row == 0 {
let cell :CategoryListBannerCell = CategoryListBannerCell()
cell.model = item
return cell
} else {
let cell : CategoryListSectionCell = tv.dequeueReusableCell(withIdentifier: "Cell2", for: ip) as! CategoryListSectionCell
cell.model = item
return cell
}
})
// 设置右边列表的代理
rightListTableView.rx.setDelegate(self).disposed(by: rx.disposeBag)
// 右边列表须要取得的数据,传递给右边列表的配置方法
rightPieceListData.map{ [CategoryRightSection(items:$0)] }.bind(to: self.rightListTableView.rx.items(dataSource: rightListDataSource))
.disposed(by: rx.disposeBag)
复制代码
上面这个实现很 Low, 选择的时机是这个 if ip.row == strongSelf.lastIndex {
, 当更新数据到指定 cell 时候,操做。数据结构
程序能够跑,可是不优雅。闭包
若是把上面的逻辑翻译成面向对象,就是:ide
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : CategoryLeftCell = tv.dequeueReusableCell(withIdentifier: "Cell1", for: ip) as! CategoryLeftCell
cell.model = item
// 看这一句代码,就够了
if ip.row == strongSelf.lastIndex {
// ...
tv.selectRow(at: ip, animated: false, scrollPosition: .top)
tv.delegate?.tableView!(tv, didSelectRowAt: ip)
// ...
}
return cell
}
复制代码
这样展开,清晰了一些。咱们是不会这么用的,若是不用 Rx, 直接 OOP. 咱们是这么用 刷新完了以后,选中一下函数
tableView.reloadData()
tv.selectRow(at: ip, animated: false, scrollPosition: .top)
复制代码
// 其余操做优化
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : CategoryLeftCell = tv.dequeueReusableCell(withIdentifier: "Cell1", for: ip) as! CategoryLeftCell
cell.model = item
return cell
}
复制代码
leftDataSource
经过泛型指明每一个 tableView section 的数据结构,他惟一的参数是一个闭包, configureCell .ui
let rightListDataSource = RxTableViewSectionedReloadDataSource<CategoryLeftSection>( configureCell: { [weak self] ds, tv, ip, item in
// ...
}
复制代码
configureCell 实际上就是系统提供的代理方法 open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
spa
RxDataSource 的源代码挺清晰的,首先采用前提条件 precondition
, row 确保不会越界。而后调用 configureCell
匿名函数。这样的设计,借用了 Swift 中函数是一级公民,函数能够像值同样传递。
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
precondition(indexPath.item < _sectionModels[indexPath.section].items.count)
return configureCell(self, tableView, indexPath, self[indexPath])
}
复制代码
继承 TableViewSectionedDataSource
, 建立本身想要的子类,任意根据需求改方法。
作一个继承
final class MyDataSource<S: SectionModelType>: RxTableViewSectionedReloadDataSource<S> {
private let relay = PublishRelay<Void>()
var rxRealoded: Signal<Void> {
return relay.asSignal()
}
override func tableView(_ tableView: UITableView, observedEvent: Event<[S]>) {
super.tableView(tableView, observedEvent: observedEvent)
// Do diff
// Notify update
relay.accept(())
}
}
复制代码
由于这个场景下, super.tableView(tableView, observedEvent: observedEvent)
, 调用以后,须要接受一下事件,之后把它发送出去。因此要用一个 PublishSubject
. PublishRelay
是对 PublishSubject
的封装,区别是他的功能没 PublishSubject
那么强,PublishRelay
少两个状态,完成 completed 和出错 error, 适合更加专门的场景。
Signal
信号嘛,共享事件流 SharedSequence。他是对 Observable
的封装。具备在主线程调用等特性,更适用于搞 UI .
简单优化下,代码语义更加明确
// left menu 数据源
let leftDataSource = MyDataSource<CategoryLeftSection>( configureCell: { ds, tv, ip, item in
let cell : CategoryLeftCell = tv.dequeueReusableCell(withIdentifier: "Cell1", for: ip) as! CategoryLeftCell
cell.model = item
return cell
})
// 刷新完了,作一下选择
leftDataSource.rxRealoded.emit(onNext: { [weak self] in
guard let self = self else { return }
let indexPath = IndexPath(row: 0, section: 0)
self.leftMenuTableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
self.leftMenuTableView.delegate?.tableView?(self.leftMenuTableView, didSelectRowAt: indexPath)
}).disposed(by: rx.disposeBag)
// ...
// 其他不变
复制代码
FRP 就是把要干吗,直接写清楚,不会像 OOP 那样,过分的见缝插针,调用到了,就改一下状态。
声明式编程是只在一处修改。就算把那一处修改,声明式编程也只在一处调用。OOP 就找的比较辛苦。
git repo , 我放在 coding.net 上面了,pod 都装好了,下载了直接跑