Skip to content

Commit

Permalink
Ensures all store operations run in the same scheduler
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
caiozullo committed Mar 21, 2024
1 parent 18fc82f commit 952ace7
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions EssentialApp/EssentialApp/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,12 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
}

func sceneWillResignActive(_ scene: UIScene) {
do {
try localFeedLoader.validateCache()
} catch {
logger.error("Failed to validate cache with error: \(error.localizedDescription)")
scheduler.schedule { [localFeedLoader, logger] in
do {
try localFeedLoader.validateCache()
} catch {
logger.error("Failed to validate cache with error: \(error.localizedDescription)")
}
}
}

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

private func makeRemoteFeedLoaderWithLocalFallback() -> AnyPublisher<Paginated<FeedImage>, Error> {
makeRemoteFeedLoader()
.receive(on: scheduler)
.caching(to: localFeedLoader)
.fallback(to: localFeedLoader.loadPublisher)
.map(makeFirstPage)
.subscribe(on: scheduler)
.eraseToAnyPublisher()
}

Expand All @@ -106,6 +108,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
(cachedItems + newItems, newItems.last)
}
.map(makePage)
.receive(on: scheduler)
.caching(to: localFeedLoader)
.subscribe(on: scheduler)
.eraseToAnyPublisher()
Expand Down Expand Up @@ -139,8 +142,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
httpClient
.getPublisher(url: url)
.tryMap(FeedImageDataMapper.map)
.receive(on: scheduler)
.caching(to: localImageLoader, using: url)
.subscribe(on: scheduler)
.eraseToAnyPublisher()
})
.subscribe(on: scheduler)
Expand Down

0 comments on commit 952ace7

Please sign in to comment.