-
Notifications
You must be signed in to change notification settings - Fork 9
/
Loadable.swift
363 lines (324 loc) · 8.94 KB
/
Loadable.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// swiftformat:disable all
/**
Loadable represents a value that can be either not loaded, loading or loaded. In the case when it has been loaded, that may or may not have succeeded.
Typically it would contain the result of calling a remote API.
if we have a `State`:
```
struct State {
@Loadable
var user: User? = nil
}
```
Then we can access an optional user instance as normal: `if let theUser = state.user { ... }` which will provide the user if it has been successfully loaded.
In some UI situations we might want to indicate if a value is still loading, failed to load etc, and then we can use something like the `LoadableView`:
```
struct LoadableView<Value, Content: View>: View {
let value: Loadable<Value>
let content: (Value) -> Content
// MARK: - Loadable
var body: some View {
switch value {
case .idle:
// Shimmer
case .loading:
// Animated shimmer or spinner
case .success(let value):
content(value)
case .failure:
// Error message or error color
}
}
}
```
The way it is used, given some `UserView` which expects a `User`, is as follows:
```
var body: some view {
LoadableView(value: state.$user) { user in
UserView(user: user)
}
}
```
The loading state of the user can be preserved when accessing its properties, if desired:
```
var body: some view {
LoadableView(value: state.$user.userName.firstName) { firstName in
Text(firstName)
}
}
```
where `state.$user.userName.firstName` is a `Loadable<String>`, similar to how `Binding` works.
*/
@propertyWrapper
@dynamicMemberLookup
public enum Loadable<Value> {
case idle
case loading
case success(Value)
case failure(Error)
public subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> Loadable<T> {
map { $0[keyPath: keyPath] }
}
public init(wrappedValue: Value?) {
self.init(wrappedValue)
}
public init(_ value: Value?) {
if let value {
self = .success(value)
} else {
self = .idle
}
}
public init(_ error: Error) {
self = .failure(error)
}
public var projectedValue: Self {
get { self }
set { self = newValue }
}
public var wrappedValue: Value? {
get {
guard case let .success(value) = self else { return nil }
return value
}
set {
self = .init(newValue)
}
}
public var isLoading: Bool {
if case .loading = self {
return true
}
return false
}
public var isSuccess: Bool {
if case .success = self {
return true
}
return false
}
public var didLoad: Bool {
switch self {
case .success, .failure:
return true
case .idle, .loading:
return false
}
}
}
extension Loadable {
public init(result: TaskResult<Value>) {
switch result {
case let .success(value):
self = .success(value)
case let .failure(error):
self = .failure(error)
}
}
}
// MARK: Equatable
extension Loadable: Equatable where Value: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case let (.success(lhs), .success(rhs)):
lhs == rhs
case let (.failure(lhs), .failure(rhs)):
_isEqual(lhs, rhs) ?? false
case (.idle, .idle):
true
case (.loading, .loading):
true
default:
false
}
}
}
// MARK: Equatable helpers
private func _isEqual(_ lhs: Any, _ rhs: Any) -> Bool? {
(lhs as? any Equatable)?.isEqual(other: rhs)
}
extension Equatable {
fileprivate func isEqual(other: Any) -> Bool {
self == other as? Self
}
}
// MARK: - Loadable + Hashable
extension Loadable: Hashable where Value: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case .idle:
hasher.combine(0)
case .loading:
hasher.combine(1)
case let .success(value):
hasher.combine(value)
hasher.combine(2)
case let .failure(error):
if let error = (error as Any) as? AnyHashable {
hasher.combine(error)
hasher.combine(4)
}
}
}
}
// MARK: - Loadable + Sendable
extension Loadable: Sendable where Value: Sendable {}
extension Loadable {
public func map<NewValue>(_ transform: (Value) -> NewValue) -> Loadable<NewValue> {
flatMap { .success(transform($0)) }
}
public func errorFallback(_ fallback: Value) -> Loadable<Value> {
if case .failure = self {
return .success(fallback)
}
return self
}
public func filter(by predicate: (Value.Element) -> Bool) -> Loadable<[Value.Element]> where Value: Sequence {
switch self {
case .idle:
return .idle
case .loading:
return .loading
case let .success(value):
return .success(value.filter(predicate))
case let .failure(error):
return .failure(error)
}
}
/// Transforms a Loadable<Wrapped?> to Loadable<Wrapped>?
public func unwrap<Wrapped>() -> Loadable<Wrapped>? where Value == Wrapped? {
switch self {
case .idle:
return .idle
case .loading:
return .loading
case let .success(value):
guard let value else {
return nil
}
return .success(value)
case let .failure(error):
return .failure(error)
}
}
public func first(where predicate: (Value.Element) -> Bool) -> Loadable<Value.Element?> where Value: Sequence {
switch self {
case .idle:
return .idle
case .loading:
return .loading
case let .success(value):
return .success(value.first(where: predicate))
case let .failure(error):
return .failure(error)
}
}
public func flatMap<NewValue>(_ transform: (Value) -> Loadable<NewValue>) -> Loadable<NewValue> {
switch self {
case .idle:
.idle
case .loading:
.loading
case let .success(value):
transform(value)
case let .failure(error):
.failure(error)
}
}
public func flatMap<NewValue>(_ transform: (Value) async -> Loadable<NewValue>) async -> Loadable<NewValue> {
switch self {
case .idle:
.idle
case .loading:
.loading
case let .success(value):
await transform(value)
case let .failure(error):
.failure(error)
}
}
public func concat<OtherValue>(_ other: Loadable<OtherValue>) -> Loadable<(Value, OtherValue)> {
switch (self, other) {
case (.idle, _), (_, .idle):
.idle
case (.loading, _), (_, .loading):
.loading
case let (.success(thisValue), .success(otherValue)):
.success((thisValue, otherValue))
case let (.failure(error), _), let (_, .failure(error)):
.failure(error)
}
}
public func flatten<InnerValue>() -> Loadable<InnerValue> where Value == Loadable<InnerValue> {
switch self {
case .idle:
return .idle
case .loading:
return .loading
case let .success(value):
return value
case .failure(let error):
return .failure(error)
}
}
public func reduce(_ other: Loadable<Value>, join: (Value, Value) -> Value) -> Loadable<Value> {
concat(other).map(join)
}
public mutating func mutateValue(_ mutate: (inout Value) -> Void) {
switch self {
case .idle, .loading, .failure:
return
case var .success(value):
mutate(&value)
self = .success(value)
}
}
/// Refreshes from other Loadable by taking into account the current `success` state.
/// This is meant to preserve the `success` state while other Loadable is `loading` or `failed`.
public mutating func refresh(
from other: Loadable<Value>,
valueChangeMap: (_ old: Value, _ new: Value) -> Value = { _, new in new }
) where Value: Equatable {
switch (self, other) {
// Update to success if no current value
case let (.idle, .success(otherValue)),
let (.loading, .success(otherValue)),
let (.failure, .success(otherValue)):
self = .success(otherValue)
// Update to new value only if it changed
case let (.success(oldValue), .success(newValue)):
if oldValue != newValue {
self = .success(valueChangeMap(oldValue, newValue))
}
// If current state is success, don't update if `other` is loading or failed
case (.success, _):
break
case (.loading, .loading),
(.idle, .idle):
break
// If current state is other than .success
case let (_, other):
self = other
}
}
}
extension Array {
func reduce<Value>(_ join: (Value, Value) -> Value) -> Loadable<Value>? where Element == Loadable<Value> {
guard var result = first else {
return nil
}
for item in dropFirst() {
result = result.reduce(item, join: join)
}
return result
}
}
extension Loadable {
/// Extract the given field either from the prefetched value or from the loaded value
public func get<Field>(_ keyPath: KeyPath<Value, Field>, prefetched: Value?) -> Loadable<Field> {
guard let prefetchedField = prefetched?[keyPath: keyPath] else {
return map { $0[keyPath: keyPath] }
}
return .success(prefetchedField)
}
}
// swiftformat:enable all