-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathDataLoader.swift
More file actions
43 lines (31 loc) · 988 Bytes
/
DataLoader.swift
File metadata and controls
43 lines (31 loc) · 988 Bytes
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
final class DataLoader<Key: Hashable, Value> {
public typealias BatchLoad = (Set<Key>) throws -> [Key: Value]
private var batchLoad: BatchLoad
private var cache: [Key: Result<Value?, any Error>] = [:]
private var pendingLoads: Set<Key> = []
public init(_ batchLoad: @escaping BatchLoad) {
self.batchLoad = batchLoad
}
subscript(key: Key) -> PossiblyDeferred<Value?> {
if let cachedResult = cache[key] {
return .immediate(cachedResult)
}
pendingLoads.insert(key)
return .deferred { try self.load(key) }
}
private func load(_ key: Key) throws -> Value? {
if let cachedResult = cache[key] {
return try cachedResult.get()
}
assert(pendingLoads.contains(key))
let values = try batchLoad(pendingLoads)
for key in pendingLoads {
cache[key] = .success(values[key])
}
pendingLoads.removeAll()
return values[key]
}
func removeAll() {
cache.removeAll()
}
}