Avoid loading cached data into memory when prefetching

This commit is contained in:
Shadowfacts 2021-01-18 14:50:56 -05:00
parent 2e88b266d9
commit e7800249af
4 changed files with 34 additions and 10 deletions

View File

@ -51,13 +51,7 @@ class ImageCache {
}
return nil
} else {
let group = RequestGroup(url: url) { (data, image) in
if let data = data {
try? self.cache.set(key, data: data)
}
self.groups.removeValueWithoutReturning(forKey: url)
}
groups[url] = group
let group = createGroup(url: url)
let request = group.addCallback(completion)
group.run()
return request
@ -65,6 +59,28 @@ class ImageCache {
}
}
func fetchIfNotCached(_ url: URL) {
// if caching is disabled, don't bother fetching since nothing will be done with the result
guard !ImageCache.disableCaching else { return }
if !((try? cache.has(url.absoluteString)) ?? false),
!groups.contains(key: url) {
let group = createGroup(url: url)
group.run()
}
}
private func createGroup(url: URL) -> RequestGroup {
let group = RequestGroup(url: url) { (data, image) in
if let data = data {
try? self.cache.set(url.absoluteString, data: data)
}
self.groups.removeValueWithoutReturning(forKey: url)
}
groups[url] = group
return group
}
func getData(_ url: URL) -> Data? {
return try? cache.getData(url.absoluteString)
}

View File

@ -47,4 +47,12 @@ class MultiThreadDictionary<Key: Hashable, Value> {
}
return value
}
func contains(key: Key) -> Bool {
var value: Bool!
queue.sync {
value = dict.keys.contains(key)
}
return value
}
}

View File

@ -213,7 +213,7 @@ extension NotificationsTableViewController: UITableViewDataSourcePrefetching {
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
for indexPath in indexPaths {
for notification in item(for: indexPath).notifications {
_ = ImageCache.avatars.get(notification.account.avatar, completion: nil)
ImageCache.avatars.fetchIfNotCached(notification.account.avatar)
}
}
}

View File

@ -21,9 +21,9 @@ extension StatusTablePrefetching {
return
}
for status in statuses {
_ = ImageCache.avatars.get(status.account.avatar, completion: nil)
ImageCache.avatars.fetchIfNotCached(status.account.avatar)
for attachment in status.attachments where attachment.kind == .image {
_ = ImageCache.attachments.get(attachment.url, completion: nil)
ImageCache.attachments.fetchIfNotCached(attachment.url)
}
}
}