-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathViewStore.swift
223 lines (211 loc) · 7.73 KB
/
ViewStore.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
import Combine
import SwiftUI
/// A `ViewStore` is an object that can observe state changes and send actions. They are most
/// commonly used in views, such as SwiftUI views, UIView or UIViewController, but they can be
/// used anywhere it makes sense to observe state and send actions.
///
/// In SwiftUI applications, a `ViewStore` is accessed most commonly using the `WithViewStore` view.
/// It can be initialized with a store and a closure that is handed a view store and must return a
/// view to be rendered:
///
/// var body: some View {
/// WithViewStore(self.store) { viewStore in
/// VStack {
/// Text("Current count: \(viewStore.count)")
/// Button("Increment") { viewStore.send(.incrementButtonTapped) }
/// }
/// }
/// }
///
/// In UIKit applications a `ViewStore` can be created from a `Store` and then subscribed to for
/// state updates:
///
/// let store: Store<State, Action>
/// let viewStore: ViewStore<State, Action>
///
/// init(store: Store<State, Action>) {
/// self.store = store
/// self.viewStore = ViewStore(store)
/// }
///
/// func viewDidLoad() {
/// super.viewDidLoad()
///
/// self.viewStore.publisher.count
/// .sink { [weak self] in self?.countLabel.text = $0 }
/// .store(in: &self.cancellables)
/// }
///
/// @objc func incrementButtonTapped() {
/// self.viewStore.send(.incrementButtonTapped)
/// }
///
@dynamicMemberLookup
public final class ViewStore<State, Action>: ObservableObject {
/// A publisher of state.
public let publisher: StorePublisher<State>
private var viewCancellable: AnyCancellable?
/// Initializes a view store from a store.
///
/// - Parameters:
/// - store: A store.
/// - isDuplicate: A function to determine when two `State` values are equal. When values are
/// equal, repeat view computations are removed.
public init(
_ store: Store<State, Action>,
removeDuplicates isDuplicate: @escaping (State, State) -> Bool
) {
let publisher = store.state.removeDuplicates(by: isDuplicate)
self.publisher = StorePublisher(publisher)
self.state = store.state.value
self._send = store.send
self.viewCancellable = publisher.sink { [weak self] in self?.state = $0 }
}
/// The current state.
public private(set) var state: State {
willSet {
self.objectWillChange.send()
}
}
let _send: (Action) -> Void
/// Returns the resulting value of a given key path.
public subscript<LocalState>(dynamicMember keyPath: KeyPath<State, LocalState>) -> LocalState {
self.state[keyPath: keyPath]
}
/// Sends an action to the store.
///
/// `ViewStore` is not thread safe and you should only send actions to it from the main thread.
/// If you are wanting to send actions on background threads due to the fact that the reducer
/// is performing computationally expensive work, then a better way to handle this is to wrap
/// that work in an `Effect` that is performed on a background thread so that the result can
/// be fed back into the store.
///
/// - Parameter action: An action.
public func send(_ action: Action) {
self._send(action)
}
/// Derives a binding from the store that prevents direct writes to state and instead sends
/// actions to the store.
///
/// The method is useful for dealing with SwiftUI components that work with two-way `Binding`s
/// since the `Store` does not allow directly writing its state; it only allows reading state and
/// sending actions.
///
/// For example, a text field binding can be created like this:
///
/// struct State { var name = "" }
/// enum Action { case nameChanged(String) }
///
/// TextField(
/// "Enter name",
/// text: viewStore.binding(
/// get: { $0.name },
/// send: { Action.nameChanged($0) }
/// )
/// )
///
/// - Parameters:
/// - get: A function to get the state for the binding from the view
/// store's full state.
/// - localStateToViewAction: A function that transforms the binding's value
/// into an action that can be sent to the store.
/// - Returns: A binding.
public func binding<LocalState>(
get: @escaping (State) -> LocalState,
send localStateToViewAction: @escaping (LocalState) -> Action
) -> Binding<LocalState> {
Binding(
get: { get(self.state) },
set: { newLocalState, transaction in
withAnimation(transaction.disablesAnimations ? nil : transaction.animation) {
self.send(localStateToViewAction(newLocalState))
}
})
}
/// Derives a binding from the store that prevents direct writes to state and instead sends
/// actions to the store.
///
/// The method is useful for dealing with SwiftUI components that work with two-way `Binding`s
/// since the `Store` does not allow directly writing its state; it only allows reading state and
/// sending actions.
///
/// For example, an alert binding can be dealt with like this:
///
/// struct State { var alert: String? }
/// enum Action { case alertDismissed }
///
/// .alert(
/// item: self.store.binding(
/// get: { $0.alert },
/// send: .alertDismissed
/// )
/// ) { alert in Alert(title: Text(alert.message)) }
///
/// - Parameters:
/// - get: A function to get the state for the binding from the view store's full state.
/// - action: The action to send when the binding is written to.
/// - Returns: A binding.
public func binding<LocalState>(
get: @escaping (State) -> LocalState,
send action: Action
) -> Binding<LocalState> {
self.binding(get: get, send: { _ in action })
}
/// Derives a binding from the store that prevents direct writes to state and instead sends
/// actions to the store.
///
/// The method is useful for dealing with SwiftUI components that work with two-way `Binding`s
/// since the `Store` does not allow directly writing its state; it only allows reading state and
/// sending actions.
///
/// For example, a text field binding can be created like this:
///
/// struct State { var name = "" }
/// enum Action { case nameChanged(String) }
///
/// TextField(
/// "Enter name",
/// text: viewStore.binding(
/// send: { Action.nameChanged($0) }
/// )
/// )
///
/// - Parameters:
/// - localStateToViewAction: A function that transforms the binding's value
/// into an action that can be sent to the store.
/// - Returns: A binding.
public func binding(
send localStateToViewAction: @escaping (State) -> Action
) -> Binding<State> {
self.binding(get: { $0 }, send: localStateToViewAction)
}
/// Derives a binding from the store that prevents direct writes to state and instead sends
/// actions to the store.
///
/// The method is useful for dealing with SwiftUI components that work with two-way `Binding`s
/// since the `Store` does not allow directly writing its state; it only allows reading state and
/// sending actions.
///
/// For example, an alert binding can be dealt with like this:
///
/// struct State { var alert: String? }
/// enum Action { case alertDismissed }
///
/// .alert(
/// item: self.store.binding(
/// send: .alertDismissed
/// )
/// ) { alert in Alert(title: Text(alert.message)) }
///
/// - Parameters:
/// - action: The action to send when the binding is written to.
/// - Returns: A binding.
public func binding(send action: Action) -> Binding<State> {
self.binding(send: { _ in action })
}
}
extension ViewStore where State: Equatable {
public convenience init(_ store: Store<State, Action>) {
self.init(store, removeDuplicates: ==)
}
}