Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up
for free
Simplifying State by partially introducing unidirectional data flow in your codebase
Benedikt Terhechte
October 13, 2017
Programming
3
470
Simplifying State by partially introducing unidirectional data flow in your codebase
Benedikt Terhechte
October 13, 2017
Tweet
Share
More Decks by Benedikt Terhechte
See All by Benedikt Terhechte
terhechte
0
30
terhechte
1
190
terhechte
15
17k
terhechte
7
1.4k
terhechte
2
210
terhechte
2
140
terhechte
3
230
terhechte
2
23k
Other Decks in Programming
See All in Programming
zwass
0
160
junmikai
0
300
brunopulis
1
100
thatjeffsmith
0
480
dictoss
0
170
ken3ypa
0
160
saki4869
0
190
kenmaz
1
100
nanimonodemonai
2
1.4k
horie1024
1
430
s_uryu
0
240
kgmyshin
0
180
Featured
See All Featured
chrislema
173
14k
wjessup
338
16k
edds
56
9.3k
deanohume
295
27k
chriscoyier
684
180k
thoeni
4
550
dotmariusz
94
5.1k
tanoku
258
24k
paulrobertlloyd
71
3.6k
kastner
54
1.9k
lemiorhan
627
43k
jasonvnalue
82
8.1k
Transcript
1
2
3
4
5
6
7
8
9
None
10
11
12
13
14
None
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/// Model struct Cinnamon { let value: Int = 0
} enum Event { case increase } 45
/// Model struct Cinnamon { let value: Int = 0
} enum Event { case increase } func reducer(state: Cinnamon, event: Event) -> Cinnamon { var newState = state if event == .increase { newState.value += 1 } return newState } /// UI let builder = Form(state: Cinnamon(), reducer: reducer) 46
47
48
49
struct AddressBook { var contacts: [Person] var searchTerm: String var
scrollPosition: Int } 50
struct AddressBookApp { struct Data { var contacts: [Person] }
var data: Data struct UI { var searchTerm: String var scrollPosition: Int } var ui: UI } 51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
private var subscribers: [String: (State)->Void] = [:] public func subscribe(_
subscriber: @escaping (State)->Void) -> String { let token = UUID().uuidString subscribers[token] = subscriber subscriber(state) return token } 66
67
protocol FormComponent { associatedtype State func setup(with state: State) func
update(state: State) -> Void } public func subscribe<Component: FormComponent> (_ subscriber: Component) -> String where Component.State == State {... 68
69
func subscribe<Type: Equatable>( path: KeyPath<Data, Type>, action: @escaping (_ oldValue:
Type, _ newValue: Type) -> Void ) -> String struct Person { let name: String } form.subscribe(path: \Person.name) { (old, new) in ... } 70
private var history: [State] = [] func apply(_ change: (inout
State) -> Void) { states.append(state) change(&state) notifySubscribers() } func undo() { state = history.popLast() notifySubscribers() } 71
72
73
74
75
76
77
78
79
80