Skip to content

Commit 952ace7

Browse files
committed
Ensures all store operations run in the same scheduler
Our Core Data store is thread-safe, so it can be safely used from any queue. However, we may want to perform store operations in a dedicated infra queue to avoid doing too much work in other queues. For example, the URLSessionHTTPClient sends results in its URLSession delegate queue. If we store the result received from the URLSessionHTTPClient in the same queue as we receive it, we may be doing too much work in the URLSession delegate queue - which could slow down the processing of other URLSessionHTTPClient results. To avoid this problem, we're now calling all store methods in a specific infra queue by using `receive(on: scheduler)` when performing a store operation after receiving results from another infra operation.
1 parent 18fc82f commit 952ace7

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

EssentialApp/EssentialApp/SceneDelegate.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,12 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
6868
}
6969

7070
func sceneWillResignActive(_ scene: UIScene) {
71-
do {
72-
try localFeedLoader.validateCache()
73-
} catch {
74-
logger.error("Failed to validate cache with error: \(error.localizedDescription)")
71+
scheduler.schedule { [localFeedLoader, logger] in
72+
do {
73+
try localFeedLoader.validateCache()
74+
} catch {
75+
logger.error("Failed to validate cache with error: \(error.localizedDescription)")
76+
}
7577
}
7678
}
7779

@@ -92,10 +94,10 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
9294

9395
private func makeRemoteFeedLoaderWithLocalFallback() -> AnyPublisher<Paginated<FeedImage>, Error> {
9496
makeRemoteFeedLoader()
97+
.receive(on: scheduler)
9598
.caching(to: localFeedLoader)
9699
.fallback(to: localFeedLoader.loadPublisher)
97100
.map(makeFirstPage)
98-
.subscribe(on: scheduler)
99101
.eraseToAnyPublisher()
100102
}
101103

@@ -106,6 +108,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
106108
(cachedItems + newItems, newItems.last)
107109
}
108110
.map(makePage)
111+
.receive(on: scheduler)
109112
.caching(to: localFeedLoader)
110113
.subscribe(on: scheduler)
111114
.eraseToAnyPublisher()
@@ -139,8 +142,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
139142
httpClient
140143
.getPublisher(url: url)
141144
.tryMap(FeedImageDataMapper.map)
145+
.receive(on: scheduler)
142146
.caching(to: localImageLoader, using: url)
143-
.subscribe(on: scheduler)
144147
.eraseToAnyPublisher()
145148
})
146149
.subscribe(on: scheduler)

0 commit comments

Comments
 (0)