20170504 RunTime





















RxCocoa, 从 OOP 到 FRP: 以 tableView 举例说明

OOP, 程序写起来,很爽。程序修修补补,想到哪里,改到哪里。问题是,自己的代码很久不看,代码思路忘记了。又要修改的时候,比较烦,代码从头看起来。全局搜索,搞起来。(看别人的代码,也是同样的感受)

FRP, 写起来,也很爽。代码都在一块,逻辑相对清晰,不用到处找。代码结构需要设计,设计好了,就有美感。有一点数据结构与算法知识的味道。设计不好,自己的编程极限就有些体现出来了。

程序是数据结构+算法。浅显一些,数据结构,就是手上有什么数据,结构化的数据,程序可以作用到的。算法,就是就是拿到数据,怎么办。

开个 tableView, 以 OOP 面向对象的方式:






读 RxCocoa 源码中的 TableView 部分: 函数柯里化,函数泛型,尾闭包

这样调用


let items = Observable.just(
            (0..<20).map { "\($0)" }
        )


items
            .bind_deng_table(to: tableView.rx.items_deng(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
                cell.textLabel?.text = "\(element) @ row \(row)"
            }
            .disposed(by: disposeBag)

有一个尾闭包,展开一下,就是


        items.bind_deng_table(to: tableView.rx.items_deng(cellIdentifier: "Cell", cellType: UITableViewCell.self)
        , curriedArgument: {
        (row, element, cell) in
        cell.textLabel?.text = "\(element) @ row \(row)"
    }).disposed(by: disposeBag)
        

知识点: 尾闭包,就是语法糖。让最后一个参数,如果是函数,就以闭包的形式。

展开后,就清晰了一些,items 是事件源,要交给 tableView 去处理。

调用了 bind_deng_table 函数,需要传进去两个参数,两个参数都是匿名函数。

看一下 bind_deng_table 这个函数:

public func bind_deng_table<R1, R2>(to binderDa: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 {
         return binderDa(self)(curriedArgument)
    }

这里有函数的柯里化,和函数的泛型。

第一个参数 binder: (Self) -> (R1) -> R2 ,对于柯里化,就是从后往前读,这个匿名函数,输出 R2, 返回 R2, 输入 (Self) -> (R1), 输入一个匿名函数 (Self) -> (R1) a, 匿名函数 a, 输入 (Self) -> 输出 (R1)

对于柯里化,我写错了

iOS---防止UIButton重复点击的三种实现方式

iOS防止Button重复点击

iOS网络请求缓冲优化HttpCachesLoader

iOS应用架构谈 网络层设计方案

IOS应用架构思考一(网络层)

RxDataSource 使用套路与解释: RxSwift 方法调用时机的转移

RxSwift 非常强大,用得好,很爽

套路: tableView 刷新以后,就是有了数据源,怎样来一个回调。

场景举例,就是两表关联。 RxDataSource,怎样列表刷新出来,就自动选择第一个。然后子列表根据上一个列表的选择,确认要刷新的数据。

问题是 RxDataSource 专注于列表视图的数据处理,自动选择第一个 row 是 tableViewDelegate 干的事情。

output.png

左边一个列表 tableView, 右边一个列表 tableView , 两个列表之间的数据存在关联,左边列表是一级选项,右边列表是对应左边的二级选项。

一般可以这么做:

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 时候,操作。

程序可以跑,但是不优雅。

如果把上面的逻辑翻译成面向对象,就是:

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 .

let rightListDataSource =  RxTableViewSectionedReloadDataSource<CategoryLeftSection>( configureCell: { [weak self] ds, tv, ip, item in
// ...
}

configureCell 实际上就是系统提供的代理方法 open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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 都装好了,下载了直接跑

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容