-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathBackgroundDatabaseObserver.swift
More file actions
204 lines (181 loc) · 8.17 KB
/
BackgroundDatabaseObserver.swift
File metadata and controls
204 lines (181 loc) · 8.17 KB
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
//
// Copyright © 2026 Stream.io Inc. All rights reserved.
//
import CoreData
import Foundation
class BackgroundDatabaseObserver<Item, DTO: NSManagedObject> {
/// Called with the aggregated changes after the internal `NSFetchResultsController` calls `controllerWillChangeContent`
/// on its delegate.
var onWillChange: (() -> Void)?
/// Called with the aggregated changes after the internal `NSFetchResultsController` calls `controllerDidChangeContent`
/// on its delegate.
var onDidChange: (([ListChange<Item>]) -> Void)?
/// Used to convert the `DTO`s to the resulting `Item`s.
private let itemCreator: (DTO) throws -> Item
private let itemReuseKeyPaths: (item: KeyPath<Item, String>, dto: KeyPath<DTO, String>)?
private let sorting: [SortValue<Item>]
/// Used to observe the changes in the DB.
private(set) var frc: NSFetchedResultsController<DTO>
/// Acts like the `NSFetchedResultsController`'s delegate and aggregates the reported changes into easily consumable form.
let changeAggregator: ListChangeAggregator<DTO, Item>
/// When called, notification observers are released
var releaseNotificationObservers: (() -> Void)?
private let queue = DispatchQueue(label: "io.getstream.list-database-observer", qos: .userInitiated)
private var _items: [Item]?
// State handling for supporting will change, because in the callback we should return the previous state.
private var _willChangeItems: [Item]?
private var _notifyingWillChange = false
/// The items that have been fetched and mapped
var rawItems: [Item] {
// During the onWillChange we swap the results back to the previous state because onWillChange
// is dispatched to the main thread and when the main thread handles it, observer has already processed
// the database change.
if onWillChange != nil {
let willChangeState: (active: Bool, cachedItems: [Item]?) = queue.sync { (_notifyingWillChange, _willChangeItems) }
if willChangeState.active {
return willChangeState.cachedItems ?? []
}
}
var rawItems: [Item]!
frc.managedObjectContext.performAndWait {
// When we already have loaded items, reuse them, otherwise refetch all
rawItems = _items ?? updateItems(nil)
}
return rawItems
}
private var _isInitialized: Bool = false
private var isInitialized: Bool {
get { queue.sync { _isInitialized } }
set { queue.async { self._isInitialized = newValue } }
}
deinit {
releaseNotificationObservers?()
}
/// Creates a new `BackgroundDatabaseObserver`.
///
/// Please note that no updates are reported until you call `startUpdating`.
///
/// - Important: ⚠️ Because the observer uses `NSFetchedResultsController` to observe the entity in the DB, it's required
/// that the provided `fetchRequest` has at lease one `NSSortDescriptor` specified.
///
/// - Parameters:
/// - fetchRequest: The `NSFetchRequest` that specifies the elements of the list.
/// - context: The `NSManagedObjectContext` the observer observes.
/// - itemCreator: A closure the observer uses to convert DTO objects into Model objects.
/// - itemReuseKeyPaths: A pair of keypaths used for reusing existing items if they have not changed
/// - sorting: An array of SortValue that define the order of the elements in the list.
/// - fetchedResultsControllerType: The `NSFetchedResultsController` subclass the observer uses to create its FRC. You can
/// inject your custom subclass if needed, i.e. when testing.
init(
context: NSManagedObjectContext,
fetchRequest: NSFetchRequest<DTO>,
itemCreator: @escaping (DTO) throws -> Item,
itemReuseKeyPaths: (item: KeyPath<Item, String>, dto: KeyPath<DTO, String>)? = nil,
sorting: [SortValue<Item>],
fetchedResultsControllerType: NSFetchedResultsController<DTO>.Type
) {
self.itemCreator = itemCreator
self.itemReuseKeyPaths = itemReuseKeyPaths
self.sorting = sorting
changeAggregator = ListChangeAggregator<DTO, Item>(itemCreator: itemCreator)
frc = fetchedResultsControllerType.init(
fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil
)
changeAggregator.onWillChange = { [weak self] in
self?.notifyWillChange()
}
changeAggregator.onDidChange = { [weak self] changes in
guard let self else { return }
// Runs on the NSManagedObjectContext's queue, therefore skip performAndWait
self.updateItems(changes)
self.notifyDidChange(changes: changes)
}
}
/// Updates the underlying fetch request's `fetchLimit` and re-runs `performFetch`
/// on the FRC's managed object context. Use this to grow (or shrink) the set of
/// items the observer exposes without tearing it down and losing delegate wiring.
func updateFetchLimit(_ newLimit: Int) {
frc.fetchRequest.fetchLimit = newLimit
frc.managedObjectContext.perform { [weak self] in
guard let self else { return }
do {
try self.frc.performFetch()
} catch {
log.error("Failed to re-fetch after updating fetchLimit to \(newLimit): \(error)")
return
}
self.updateItems(nil)
}
}
/// Starts observing the changes in the database.
/// - Throws: An error if the fetch fails.
func startObserving() throws {
guard !isInitialized else { return }
isInitialized = true
do {
try frc.performFetch()
} catch {
log.error("Failed to start observing database: \(error). This is an internal error.")
throw error
}
frc.delegate = changeAggregator
// Start loading initial items and call did change for the initial change.
frc.managedObjectContext.perform { [weak self] in
guard let self else { return }
let items = self.updateItems(nil)
let changes: [ListChange<Item>] = items.enumerated().map { .insert($1, index: IndexPath(item: $0, section: 0)) }
self.notifyDidChange(changes: changes)
}
}
private func notifyWillChange() {
guard let onWillChange = onWillChange else {
return
}
// Will change callback happens on the main thread but by that time the observer
// has already updated its local cached state. For allowing to access the previous
// state from the will change callback, there is no other way than caching previous state.
// This is used by the channel list delegate.
// `_items` is mutated by the NSManagedObjectContext's queue, here we are on that queue
// so it is safe to read the `_items` state from `self.queue`.
queue.sync {
_willChangeItems = _items
}
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.queue.async {
self._notifyingWillChange = true
}
onWillChange()
self.queue.async {
self._willChangeItems = nil
self._notifyingWillChange = false
}
}
}
private func notifyDidChange(changes: [ListChange<Item>]) {
guard let onDidChange = onDidChange else {
return
}
DispatchQueue.main.async {
onDidChange(changes)
}
}
/// Updates the locally cached items.
///
/// - Important: Must be called from the managed object's perform closure.
@discardableResult private func updateItems(_ changes: [ListChange<Item>]?) -> [Item] {
let items = DatabaseItemConverter.convert(
dtos: frc.fetchedObjects ?? [],
existing: _items ?? [],
changes: changes,
itemCreator: itemCreator,
itemReuseKeyPaths: itemReuseKeyPaths,
sorting: sorting
)
_items = items
return items
}
}