-
Notifications
You must be signed in to change notification settings - Fork 290
/
01-GettingStarted-SharedState.swift
291 lines (254 loc) · 6.88 KB
/
01-GettingStarted-SharedState.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import ComposableArchitecture
import SwiftUI
private let readMe = """
This screen demonstrates how multiple independent screens can share state in the Composable \
Architecture. Each tab manages its own state, and could be in separate modules, but changes in \
one tab are immediately reflected in the other.
This tab has its own state, consisting of a count value that can be incremented and decremented, \
as well as an alert value that is set when asking if the current count is prime.
Internally, it is also keeping track of various stats, such as min and max counts and total \
number of count events that occurred. Those states are viewable in the other tab, and the stats \
can be reset from the other tab.
"""
@Reducer
struct CounterTab {
@ObservableState
struct State: Equatable {
@Presents var alert: AlertState<Action.Alert>?
@Shared var stats: Stats
}
enum Action {
case alert(PresentationAction<Alert>)
case decrementButtonTapped
case incrementButtonTapped
case isPrimeButtonTapped
enum Alert: Equatable {}
}
var body: some Reducer<State, Action> {
Reduce { state, action in
switch action {
case .alert:
return .none
case .decrementButtonTapped:
state.stats.decrement()
return .none
case .incrementButtonTapped:
state.stats.increment()
return .none
case .isPrimeButtonTapped:
state.alert = AlertState {
TextState(
isPrime(state.stats.count)
? "👍 The number \(state.stats.count) is prime!"
: "👎 The number \(state.stats.count) is not prime :("
)
}
return .none
}
}
.ifLet(\.$alert, action: \.alert)
}
}
struct CounterTabView: View {
@Bindable var store: StoreOf<CounterTab>
var body: some View {
Form {
Text(template: readMe, .caption)
VStack(spacing: 16) {
HStack {
Button {
store.send(.decrementButtonTapped)
} label: {
Image(systemName: "minus")
}
Text("\(store.stats.count)")
.monospacedDigit()
Button {
store.send(.incrementButtonTapped)
} label: {
Image(systemName: "plus")
}
}
Button("Is this prime?") { store.send(.isPrimeButtonTapped) }
}
}
.buttonStyle(.borderless)
.navigationTitle("Shared State Demo")
.alert($store.scope(state: \.alert, action: \.alert))
}
}
@Reducer
struct ProfileTab {
@ObservableState
struct State: Equatable {
@Shared var stats: Stats
}
enum Action {
case resetStatsButtonTapped
}
var body: some Reducer<State, Action> {
Reduce { state, action in
switch action {
case .resetStatsButtonTapped:
state.stats.reset()
return .none
}
}
}
}
struct ProfileTabView: View {
let store: StoreOf<ProfileTab>
var body: some View {
Form {
Text(
template: """
This tab shows state from the previous tab, and it is capable of reseting all of the \
state back to 0.
This shows that it is possible for each screen to model its state in the way that makes \
the most sense for it, while still allowing the state and mutations to be shared \
across independent screens.
""",
.caption
)
VStack(spacing: 16) {
Text("Current count: \(store.stats.count)")
Text("Max count: \(store.stats.maxCount)")
Text("Min count: \(store.stats.minCount)")
Text("Total number of count events: \(store.stats.numberOfCounts)")
Button("Reset") { store.send(.resetStatsButtonTapped) }
}
}
.buttonStyle(.borderless)
.navigationTitle("Profile")
}
}
@Reducer
struct SharedState {
enum Tab { case counter, profile }
@ObservableState
struct State: Equatable {
var currentTab = Tab.counter
var counter: CounterTab.State
var profile: ProfileTab.State
@Shared var stats: Stats
init(
currentTab: Tab = Tab.counter,
stats sharedStats: Shared<Stats> = Shared(Stats())
) {
self.currentTab = currentTab
self.counter = CounterTab.State(stats: sharedStats)
self.profile = ProfileTab.State(stats: sharedStats)
self._stats = sharedStats
}
}
enum Action {
case counter(CounterTab.Action)
case profile(ProfileTab.Action)
case selectTab(Tab)
}
var body: some Reducer<State, Action> {
Scope(state: \.counter, action: \.counter) {
CounterTab()
}
// .onChange(of: \.counter.stats) { _, stats in
// Reduce { state, _ in
// state.profile.stats = stats
// return .none
// }
// }
Scope(state: \.profile, action: \.profile) {
ProfileTab()
}
// .onChange(of: \.profile.stats) { _, stats in
// Reduce { state, _ in
// state.counter.stats = stats
// return .none
// }
// }
Reduce { state, action in
switch action {
case .counter, .profile:
return .none
case let .selectTab(tab):
state.currentTab = tab
state.stats.increment()
return .none
}
}
}
}
struct SharedStateView: View {
@Bindable var store: StoreOf<SharedState>
var body: some View {
TabView(selection: $store.currentTab.sending(\.selectTab)) {
NavigationStack {
CounterTabView(
store: self.store.scope(state: \.counter, action: \.counter)
)
}
.tag(SharedState.Tab.counter)
.tabItem { Text("Counter") }
NavigationStack {
ProfileTabView(
store: self.store.scope(state: \.profile, action: \.profile)
)
}
.tag(SharedState.Tab.profile)
.tabItem { Text("Profile") }
}
}
}
class CounterModel: ObservableObject {
@Published var count = 0
}
@propertyWrapper
@Observable
final class Shared<Value> {
var wrappedValue: Value
init(_ wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var projectedValue: Shared {
self
}
}
extension Shared: Equatable where Value: Equatable {
static func == (lhs: Shared, rhs: Shared) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
struct Stats: Equatable {
private(set) var count = 0
private(set) var maxCount = 0
private(set) var minCount = 0
private(set) var numberOfCounts = 0
mutating func increment() {
count += 1
numberOfCounts += 1
maxCount = max(maxCount, count)
}
mutating func decrement() {
count -= 1
numberOfCounts += 1
minCount = min(minCount, count)
}
mutating func reset() {
self = Self()
}
}
/// Checks if a number is prime or not.
private func isPrime(_ p: Int) -> Bool {
if p <= 1 { return false }
if p <= 3 { return true }
for i in 2...Int(sqrtf(Float(p))) {
if p % i == 0 { return false }
}
return true
}
#Preview {
SharedStateView(
store: Store(initialState: SharedState.State()) {
SharedState()
}
)
}