Skip to content

Commit 1343359

Browse files
committed
Demo: improved RemoteImage and ImageCache modules
1 parent 54b2bac commit 1343359

File tree

2 files changed

+11
-16
lines changed

2 files changed

+11
-16
lines changed

AsyncMuxDemo/Sources/RemoteImage/ImageCache.swift

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,41 +12,31 @@ import AsyncMux
1212
private let CacheCapacity = 20
1313

1414

15+
@MainActor
1516
final class ImageCache {
1617

1718
static func request(_ url: URL) async throws -> UIImage {
1819
if let image = loadFromMemory(url) {
1920
return image
2021
}
2122
let image = try await requestRemote(url)
22-
storeToMemory(url: url, image: image)
23+
memCache.set(image, forKey: url)
2324
return image
2425
}
2526

2627

2728
static func loadFromMemory(_ url: URL) -> UIImage? {
28-
semaphore.wait()
29-
defer { semaphore.signal() }
30-
return memCache.touch(key: url)
29+
memCache.touch(key: url)
3130
}
3231

3332

3433
static func clear() {
35-
semaphore.wait()
36-
defer { semaphore.signal() }
3734
memCache.removeAll()
3835
}
3936

40-
37+
4138
// MARK: - Private part
4239

43-
private static func storeToMemory(url: URL, image: UIImage) {
44-
semaphore.wait()
45-
defer { semaphore.signal() }
46-
memCache.set(image, forKey: url)
47-
}
48-
49-
5040
@AsyncMediaActor
5141
private static func requestRemote(_ url: URL) async throws -> UIImage {
5242
let localURL = try await AsyncMedia.request(url: url)
@@ -58,8 +48,7 @@ final class ImageCache {
5848
}
5949

6050

61-
nonisolated(unsafe)
6251
private static var memCache = LRUCache<URL, UIImage>(capacity: CacheCapacity)
6352

64-
private static let semaphore = DispatchSemaphore(value: 1)
53+
private init() { }
6554
}

AsyncMuxDemo/Sources/RemoteImage/RemoteImage.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,17 @@ struct RemoteImage<P: View, I: View>: View {
2828
}
2929
}
3030
.onChange(of: url, initial: true) { oldValue, newValue in
31+
// Try sync load first
32+
if let newValue, let image = ImageCache.loadFromMemory(newValue) {
33+
uiImage = image
34+
return
35+
}
3136
uiImage = nil
3237
error = nil
3338
if let newValue {
3439
Task {
3540
do {
41+
// Now try loading from disk or downloading remote
3642
self.uiImage = try await ImageCache.request(newValue)
3743
}
3844
catch {

0 commit comments

Comments
 (0)