英文原文:Part 1 --- Why Redux on iOS
**你在哪里:**第一阶段,动机。
**读完本篇你会知道:**iOS 应用变大之后会冒出哪些具体的状态问题,为什么 MVC(Model-View-Controller,模型-视图-控制器)和 MVVM(Model-View-ViewModel,模型-视图-视图模型)单靠自己解决不了,以及 Redux 的思想从何而来。
缩写对照表
| 缩写 | 英文全称 | 中文 |
|---|---|---|
| MVC | Model-View-Controller | 模型-视图-控制器 |
| MVVM | Model-View-ViewModel | 模型-视图-视图模型 |
| VC | View Controller | 视图控制器 |
| UI | User Interface | 用户界面 |
| JS | JavaScript | JavaScript 脚本语言 |
| TCA | The Composable Architecture | 可组合架构 |
1.1 一个会出问题的小应用
设想一个没有任何架构的 ShopList。它有两个页面:
- 列表(List)(UIKit):一张商品表格,点一下就标记为已购买。
- 汇总(Summary)(另一个标签页):显示「还有 2/3 件要买」,外加已购商品列表。
最快的写法是在每个视图控制器(VC)里各存一个 items 数组。用户在列表页点了「牛奶」,这个视图控制器更新自己的 数组并刷新表格,而汇总页手里还是旧的那份。于是你加一个 delegate,或者发一条 NotificationCenter 通知,或者弄一个带回调的 ItemsManager 单例。接着要从服务器加载数据,两个页面都得显示加载动画。然后要存盘。再然后,汇总页要加一个「清空已购」按钮,还得同步更新列表页。
几轮下来,代码就成了这样:
swift
// ListViewController
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
items[indexPath.row].isBought.toggle() // 1. local copy
ItemsManager.shared.items = items // 2. shared copy
NotificationCenter.default.post(name: .itemsChanged, object: nil) // 3. tell others
ItemsManager.shared.save() // 4. side effect
tableView.reloadRows(at: [indexPath], with: .automatic) // 5. update UI
updateBadge() // 6. derived UI elsewhere
}
每一行都可能被漏掉,而同样的步骤还要复制到每一个修改数据的地方。
1.2 给问题起个名字
| # | 问题 | 在 ShopList 里的症状 |
|---|---|---|
| P1 | 状态重复 | 列表页和汇总页各存一个 items 数组;点一下之后两者就对不上了 |
| P2 | 修改来自四面八方 | 任何视图控制器、网络回调或后台任务都能写 ItemsManager.items |
| P3 | bug 难以解释 | 「牛奶显示已购买,但计数说还剩 3 件。」是 6 个写入方里的哪一个干的?顺序又是怎样的? |
| P4 | 副作用混在 UI 代码里 | 网络请求和存盘都写在 didSelectRowAt 里;离开 UI 就没法测试这段逻辑 |
| P5 | 隐藏的异步竞态 | 一个慢吞吞的服务器响应,覆盖掉了用户刚刚添加的商品 |
| P6 | 派生值逐渐失真 | remainingCount 被存下来再手动更新,迟早会过期 |
1.3 为什么单靠 MVC 和 MVVM 解决不了
MVC 把逻辑放在视图控制器里。页面一多,每个视图控制器都成了数据的一个小主人,这正是 P1 和 P2。
MVVM 把逻辑挪进 view model,让页面变得可测试。但每个 view model 通常仍然拥有 自己的状态。两个展示同一批商品的 view model 依然需要某种方式保持同步,所以 P1 和 P3 还在。MVVM 关心的是一个页面 内部怎么组织,对状态如何跨页面共享则只字未提。
Redux 回答的正是第二个问题:应用的所有状态只有一个主人,修改它也只有一条路。
1.4 思想从何而来
Redux 从哪里来,又是怎么传到 iOS 的?
#mermaid-svg-4SBfg34CgZIYwNGC{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-4SBfg34CgZIYwNGC .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-4SBfg34CgZIYwNGC .error-icon{fill:#552222;}#mermaid-svg-4SBfg34CgZIYwNGC .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-4SBfg34CgZIYwNGC .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-4SBfg34CgZIYwNGC .marker{fill:#333333;stroke:#333333;}#mermaid-svg-4SBfg34CgZIYwNGC .marker.cross{stroke:#333333;}#mermaid-svg-4SBfg34CgZIYwNGC svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-4SBfg34CgZIYwNGC p{margin:0;}#mermaid-svg-4SBfg34CgZIYwNGC .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-4SBfg34CgZIYwNGC .cluster-label text{fill:#333;}#mermaid-svg-4SBfg34CgZIYwNGC .cluster-label span{color:#333;}#mermaid-svg-4SBfg34CgZIYwNGC .cluster-label span p{background-color:transparent;}#mermaid-svg-4SBfg34CgZIYwNGC .label text,#mermaid-svg-4SBfg34CgZIYwNGC span{fill:#333;color:#333;}#mermaid-svg-4SBfg34CgZIYwNGC .node rect,#mermaid-svg-4SBfg34CgZIYwNGC .node circle,#mermaid-svg-4SBfg34CgZIYwNGC .node ellipse,#mermaid-svg-4SBfg34CgZIYwNGC .node polygon,#mermaid-svg-4SBfg34CgZIYwNGC .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-4SBfg34CgZIYwNGC .rough-node .label text,#mermaid-svg-4SBfg34CgZIYwNGC .node .label text,#mermaid-svg-4SBfg34CgZIYwNGC .image-shape .label,#mermaid-svg-4SBfg34CgZIYwNGC .icon-shape .label{text-anchor:middle;}#mermaid-svg-4SBfg34CgZIYwNGC .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-4SBfg34CgZIYwNGC .rough-node .label,#mermaid-svg-4SBfg34CgZIYwNGC .node .label,#mermaid-svg-4SBfg34CgZIYwNGC .image-shape .label,#mermaid-svg-4SBfg34CgZIYwNGC .icon-shape .label{text-align:center;}#mermaid-svg-4SBfg34CgZIYwNGC .node.clickable{cursor:pointer;}#mermaid-svg-4SBfg34CgZIYwNGC .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-4SBfg34CgZIYwNGC .arrowheadPath{fill:#333333;}#mermaid-svg-4SBfg34CgZIYwNGC .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-4SBfg34CgZIYwNGC .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-4SBfg34CgZIYwNGC .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-4SBfg34CgZIYwNGC .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-4SBfg34CgZIYwNGC .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-4SBfg34CgZIYwNGC .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-4SBfg34CgZIYwNGC .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-4SBfg34CgZIYwNGC .cluster text{fill:#333;}#mermaid-svg-4SBfg34CgZIYwNGC .cluster span{color:#333;}#mermaid-svg-4SBfg34CgZIYwNGC div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-4SBfg34CgZIYwNGC .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-4SBfg34CgZIYwNGC rect.text{fill:none;stroke-width:0;}#mermaid-svg-4SBfg34CgZIYwNGC .icon-shape,#mermaid-svg-4SBfg34CgZIYwNGC .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-4SBfg34CgZIYwNGC .icon-shape p,#mermaid-svg-4SBfg34CgZIYwNGC .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-4SBfg34CgZIYwNGC .icon-shape .label rect,#mermaid-svg-4SBfg34CgZIYwNGC .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-4SBfg34CgZIYwNGC .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-4SBfg34CgZIYwNGC .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-4SBfg34CgZIYwNGC :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Elm 架构
(Model、Update、View)
Redux,2015
Abramov 与 Clark(JS)
Flux,Facebook 2014
单向数据流
ReSwift,2015
Swift 版 Redux
TCA,2020
Point-Free(Swift)
手写的 store
(本系列)
- Flux(Facebook,2014)引入了单向数据流:action → dispatcher → store → 视图。
- Elm 架构 说明了 UI 更新可以写成一个纯函数:
update : Msg -> Model -> Model。 - Redux(2015)把两者合成一套简洁的规则:单一 store,加上纯函数 reducer。
- 在 iOS 上,ReSwift 几乎一比一地移植了 Redux;**TCA(The Composable Architecture,可组合架构)**从同一个源头长成了一个更大的框架。还有很多团队自己写一个小 store,Accenture 那篇文章是这么做的,本系列也是。
1.5 Redux 带来了什么
| 问题 | Redux 的答案 |
|---|---|
| P1 状态重复 | 一个 store,一个状态值。 页面从它读取,不再各自保留副本 |
| P2 修改来自四面八方 | 只有 dispatch(action) 能修改状态,而且只由 reducer 决定怎么改 |
| P3 bug 难以解释 | 每次修改都是一个可以记录下来的 action ;这份日志就是应用的历史 |
| P4 副作用混在 UI 里 | 副作用放在 middleware 里;reducer 和视图都是纯的,可以测试 |
| P5 异步竞态 | 异步工作以派发另一个 action 收尾,所以结果会经由同一个 reducer 按顺序生效 |
| P6 派生值失真 | 派生值是 selector,从状态中计算得出,从不单独存储 |
代价是更多的结构:每个事件一个 action,每个 action 一个 reducer 分支,外加要搭建一个 store。第 7 篇(英文)会如实地掂量这个代价。
← 00 · 系列导读 · 下一篇 → 02 · Redux 是什么,又不是什么(英文)